prompt_id
int64
0
941
project
stringclasses
24 values
module
stringlengths
7
49
class
stringlengths
0
32
method
stringlengths
2
37
focal_method_txt
stringlengths
43
41.5k
focal_method_lines
listlengths
2
2
in_stack
bool
2 classes
globals
listlengths
0
16
type_context
stringlengths
79
41.9k
has_branch
bool
2 classes
total_branches
int64
0
3
100
httpie
httpie.cli.definition
_AuthTypeLazyChoices
__contains__
def __contains__(self, item): return item in plugin_manager.get_auth_plugin_mapping()
[ 522, 523 ]
false
[ "parser", "positional", "content_type", "content_processing", "output_processing", "_sorted_kwargs", "_unsorted_kwargs", "output_options", "sessions", "session_name_validator", "auth", "_auth_plugins", "network", "ssl", "troubleshooting" ]
from argparse import (FileType, OPTIONAL, SUPPRESS, ZERO_OR_MORE) from textwrap import dedent, wrap from httpie import __doc__, __version__ from httpie.cli.argparser import HTTPieArgumentParser from httpie.cli.argtypes import ( KeyValueArgType, SessionNameValidator, readable_file_arg, ) from httpie.cli.constants import ( DEFAULT_FORMAT_OPTIONS, OUTPUT_OPTIONS, OUTPUT_OPTIONS_DEFAULT, OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD, PRETTY_MAP, PRETTY_STDOUT_TTY_ONLY, RequestType, SEPARATOR_GROUP_ALL_ITEMS, SEPARATOR_PROXY, SORTED_FORMAT_OPTIONS_STRING, UNSORTED_FORMAT_OPTIONS_STRING, ) from httpie.output.formatters.colors import ( AUTO_STYLE, AVAILABLE_STYLES, DEFAULT_STYLE, ) from httpie.plugins.builtin import BuiltinAuthPlugin from httpie.plugins.registry import plugin_manager from httpie.sessions import DEFAULT_SESSIONS_DIR from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, DEFAULT_SSL_CIPHERS parser = HTTPieArgumentParser( prog='http', description='%s <https://httpie.org>' % __doc__.strip(), epilog=dedent(''' For every --OPTION there is also a --no-OPTION that reverts OPTION to its default value. Suggestions and bug reports are greatly appreciated: https://github.com/httpie/httpie/issues '''), ) positional = parser.add_argument_group( title='Positional Arguments', description=dedent(''' These arguments come after any flags and in the order they are listed here. Only URL is required. ''') ) content_type = parser.add_argument_group( title='Predefined Content Types', description=None ) content_processing = parser.add_argument_group( title='Content Processing Options', description=None ) output_processing = parser.add_argument_group(title='Output Processing') _sorted_kwargs = { 'action': 'append_const', 'const': SORTED_FORMAT_OPTIONS_STRING, 'dest': 'format_options' } _unsorted_kwargs = { 'action': 'append_const', 'const': UNSORTED_FORMAT_OPTIONS_STRING, 'dest': 'format_options' } output_options = parser.add_argument_group(title='Output Options') sessions = parser.add_argument_group(title='Sessions') \ .add_mutually_exclusive_group(required=False) session_name_validator = SessionNameValidator( 'Session name contains invalid characters.' ) auth = parser.add_argument_group(title='Authentication') _auth_plugins = plugin_manager.get_auth_plugins() network = parser.add_argument_group(title='Network') ssl = parser.add_argument_group(title='SSL') troubleshooting = parser.add_argument_group(title='Troubleshooting') class _AuthTypeLazyChoices: # Needed for plugin testing def __contains__(self, item): return item in plugin_manager.get_auth_plugin_mapping()
false
0
101
httpie
httpie.cli.definition
_AuthTypeLazyChoices
__iter__
def __iter__(self): return iter(sorted(plugin_manager.get_auth_plugin_mapping().keys()))
[ 525, 526 ]
false
[ "parser", "positional", "content_type", "content_processing", "output_processing", "_sorted_kwargs", "_unsorted_kwargs", "output_options", "sessions", "session_name_validator", "auth", "_auth_plugins", "network", "ssl", "troubleshooting" ]
from argparse import (FileType, OPTIONAL, SUPPRESS, ZERO_OR_MORE) from textwrap import dedent, wrap from httpie import __doc__, __version__ from httpie.cli.argparser import HTTPieArgumentParser from httpie.cli.argtypes import ( KeyValueArgType, SessionNameValidator, readable_file_arg, ) from httpie.cli.constants import ( DEFAULT_FORMAT_OPTIONS, OUTPUT_OPTIONS, OUTPUT_OPTIONS_DEFAULT, OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD, PRETTY_MAP, PRETTY_STDOUT_TTY_ONLY, RequestType, SEPARATOR_GROUP_ALL_ITEMS, SEPARATOR_PROXY, SORTED_FORMAT_OPTIONS_STRING, UNSORTED_FORMAT_OPTIONS_STRING, ) from httpie.output.formatters.colors import ( AUTO_STYLE, AVAILABLE_STYLES, DEFAULT_STYLE, ) from httpie.plugins.builtin import BuiltinAuthPlugin from httpie.plugins.registry import plugin_manager from httpie.sessions import DEFAULT_SESSIONS_DIR from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, DEFAULT_SSL_CIPHERS parser = HTTPieArgumentParser( prog='http', description='%s <https://httpie.org>' % __doc__.strip(), epilog=dedent(''' For every --OPTION there is also a --no-OPTION that reverts OPTION to its default value. Suggestions and bug reports are greatly appreciated: https://github.com/httpie/httpie/issues '''), ) positional = parser.add_argument_group( title='Positional Arguments', description=dedent(''' These arguments come after any flags and in the order they are listed here. Only URL is required. ''') ) content_type = parser.add_argument_group( title='Predefined Content Types', description=None ) content_processing = parser.add_argument_group( title='Content Processing Options', description=None ) output_processing = parser.add_argument_group(title='Output Processing') _sorted_kwargs = { 'action': 'append_const', 'const': SORTED_FORMAT_OPTIONS_STRING, 'dest': 'format_options' } _unsorted_kwargs = { 'action': 'append_const', 'const': UNSORTED_FORMAT_OPTIONS_STRING, 'dest': 'format_options' } output_options = parser.add_argument_group(title='Output Options') sessions = parser.add_argument_group(title='Sessions') \ .add_mutually_exclusive_group(required=False) session_name_validator = SessionNameValidator( 'Session name contains invalid characters.' ) auth = parser.add_argument_group(title='Authentication') _auth_plugins = plugin_manager.get_auth_plugins() network = parser.add_argument_group(title='Network') ssl = parser.add_argument_group(title='SSL') troubleshooting = parser.add_argument_group(title='Troubleshooting') class _AuthTypeLazyChoices: # Needed for plugin testing def __iter__(self): return iter(sorted(plugin_manager.get_auth_plugin_mapping().keys()))
false
0
102
httpie
httpie.cli.requestitems
process_file_upload_arg
def process_file_upload_arg(arg: KeyValueArg) -> Tuple[str, IO, str]: parts = arg.value.split(SEPARATOR_FILE_UPLOAD_TYPE) filename = parts[0] mime_type = parts[1] if len(parts) > 1 else None try: f = open(os.path.expanduser(filename), 'rb') except IOError as e: raise ParseError('"%s": %s' % (arg.orig, e)) return ( os.path.basename(filename), f, mime_type or get_content_type(filename), )
[ 104, 112 ]
false
[ "JSONType" ]
import os from typing import Callable, Dict, IO, List, Optional, Tuple, Union from httpie.cli.argtypes import KeyValueArg from httpie.cli.constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEPARATOR_FILE_UPLOAD, SEPARATOR_FILE_UPLOAD_TYPE, SEPARATOR_HEADER, SEPARATOR_HEADER_EMPTY, SEPARATOR_QUERY_PARAM, ) from httpie.cli.dicts import ( MultipartRequestDataDict, RequestDataDict, RequestFilesDict, RequestHeadersDict, RequestJSONDataDict, RequestQueryParamsDict, ) from httpie.cli.exceptions import ParseError from httpie.utils import (get_content_type, load_json_preserve_order) JSONType = Union[str, bool, int, list, dict] def process_file_upload_arg(arg: KeyValueArg) -> Tuple[str, IO, str]: parts = arg.value.split(SEPARATOR_FILE_UPLOAD_TYPE) filename = parts[0] mime_type = parts[1] if len(parts) > 1 else None try: f = open(os.path.expanduser(filename), 'rb') except IOError as e: raise ParseError('"%s": %s' % (arg.orig, e)) return ( os.path.basename(filename), f, mime_type or get_content_type(filename), )
false
0
103
httpie
httpie.cli.requestitems
process_data_embed_raw_json_file_arg
def process_data_embed_raw_json_file_arg(arg: KeyValueArg) -> JSONType: contents = load_text_file(arg) value = load_json(arg, contents) return value
[ 127, 130 ]
false
[ "JSONType" ]
import os from typing import Callable, Dict, IO, List, Optional, Tuple, Union from httpie.cli.argtypes import KeyValueArg from httpie.cli.constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEPARATOR_FILE_UPLOAD, SEPARATOR_FILE_UPLOAD_TYPE, SEPARATOR_HEADER, SEPARATOR_HEADER_EMPTY, SEPARATOR_QUERY_PARAM, ) from httpie.cli.dicts import ( MultipartRequestDataDict, RequestDataDict, RequestFilesDict, RequestHeadersDict, RequestJSONDataDict, RequestQueryParamsDict, ) from httpie.cli.exceptions import ParseError from httpie.utils import (get_content_type, load_json_preserve_order) JSONType = Union[str, bool, int, list, dict] def process_data_embed_raw_json_file_arg(arg: KeyValueArg) -> JSONType: contents = load_text_file(arg) value = load_json(arg, contents) return value
false
0
104
httpie
httpie.cli.requestitems
process_data_raw_json_embed_arg
def process_data_raw_json_embed_arg(arg: KeyValueArg) -> JSONType: value = load_json(arg, arg.value) return value
[ 133, 135 ]
false
[ "JSONType" ]
import os from typing import Callable, Dict, IO, List, Optional, Tuple, Union from httpie.cli.argtypes import KeyValueArg from httpie.cli.constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEPARATOR_FILE_UPLOAD, SEPARATOR_FILE_UPLOAD_TYPE, SEPARATOR_HEADER, SEPARATOR_HEADER_EMPTY, SEPARATOR_QUERY_PARAM, ) from httpie.cli.dicts import ( MultipartRequestDataDict, RequestDataDict, RequestFilesDict, RequestHeadersDict, RequestJSONDataDict, RequestQueryParamsDict, ) from httpie.cli.exceptions import ParseError from httpie.utils import (get_content_type, load_json_preserve_order) JSONType = Union[str, bool, int, list, dict] def process_data_raw_json_embed_arg(arg: KeyValueArg) -> JSONType: value = load_json(arg, arg.value) return value
false
0
105
httpie
httpie.cli.requestitems
load_text_file
def load_text_file(item: KeyValueArg) -> str: path = item.value try: with open(os.path.expanduser(path), 'rb') as f: return f.read().decode() except IOError as e: raise ParseError('"%s": %s' % (item.orig, e)) except UnicodeDecodeError: raise ParseError( '"%s": cannot embed the content of "%s",' ' not a UTF8 or ASCII-encoded text file' % (item.orig, item.value) )
[ 138, 146 ]
false
[ "JSONType" ]
import os from typing import Callable, Dict, IO, List, Optional, Tuple, Union from httpie.cli.argtypes import KeyValueArg from httpie.cli.constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEPARATOR_FILE_UPLOAD, SEPARATOR_FILE_UPLOAD_TYPE, SEPARATOR_HEADER, SEPARATOR_HEADER_EMPTY, SEPARATOR_QUERY_PARAM, ) from httpie.cli.dicts import ( MultipartRequestDataDict, RequestDataDict, RequestFilesDict, RequestHeadersDict, RequestJSONDataDict, RequestQueryParamsDict, ) from httpie.cli.exceptions import ParseError from httpie.utils import (get_content_type, load_json_preserve_order) JSONType = Union[str, bool, int, list, dict] def load_text_file(item: KeyValueArg) -> str: path = item.value try: with open(os.path.expanduser(path), 'rb') as f: return f.read().decode() except IOError as e: raise ParseError('"%s": %s' % (item.orig, e)) except UnicodeDecodeError: raise ParseError( '"%s": cannot embed the content of "%s",' ' not a UTF8 or ASCII-encoded text file' % (item.orig, item.value) )
false
0
106
httpie
httpie.client
collect_messages
def collect_messages( args: argparse.Namespace, config_dir: Path, request_body_read_callback: Callable[[bytes], None] = None, ) -> Iterable[Union[requests.PreparedRequest, requests.Response]]: httpie_session = None httpie_session_headers = None if args.session or args.session_read_only: httpie_session = get_httpie_session( config_dir=config_dir, session_name=args.session or args.session_read_only, host=args.headers.get('Host'), url=args.url, ) httpie_session_headers = httpie_session.headers request_kwargs = make_request_kwargs( args=args, base_headers=httpie_session_headers, request_body_read_callback=request_body_read_callback ) send_kwargs = make_send_kwargs(args) send_kwargs_mergeable_from_env = make_send_kwargs_mergeable_from_env(args) requests_session = build_requests_session( ssl_version=args.ssl_version, ciphers=args.ciphers, verify=bool(send_kwargs_mergeable_from_env['verify']) ) if httpie_session: httpie_session.update_headers(request_kwargs['headers']) requests_session.cookies = httpie_session.cookies if args.auth_plugin: # Save auth from CLI to HTTPie session. httpie_session.auth = { 'type': args.auth_plugin.auth_type, 'raw_auth': args.auth_plugin.raw_auth, } elif httpie_session.auth: # Apply auth from HTTPie session request_kwargs['auth'] = httpie_session.auth if args.debug: # TODO: reflect the split between request and send kwargs. dump_request(request_kwargs) request = requests.Request(**request_kwargs) prepared_request = requests_session.prepare_request(request) if args.path_as_is: prepared_request.url = ensure_path_as_is( orig_url=args.url, prepped_url=prepared_request.url, ) if args.compress and prepared_request.body: compress_request( request=prepared_request, always=args.compress > 1, ) response_count = 0 expired_cookies = [] while prepared_request: yield prepared_request if not args.offline: send_kwargs_merged = requests_session.merge_environment_settings( url=prepared_request.url, **send_kwargs_mergeable_from_env, ) with max_headers(args.max_headers): response = requests_session.send( request=prepared_request, **send_kwargs_merged, **send_kwargs, ) # noinspection PyProtectedMember expired_cookies += get_expired_cookies( headers=response.raw._original_response.msg._headers ) response_count += 1 if response.next: if args.max_redirects and response_count == args.max_redirects: raise requests.TooManyRedirects if args.follow: prepared_request = response.next if args.all: yield response continue yield response break if httpie_session: if httpie_session.is_new() or not args.session_read_only: httpie_session.cookies = requests_session.cookies httpie_session.remove_cookies( # TODO: take path & domain into account? cookie['name'] for cookie in expired_cookies ) httpie_session.save()
[ 32, 130 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDict from httpie.plugins.registry import plugin_manager from httpie.sessions import get_httpie_session from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter from httpie.uploads import ( compress_request, prepare_request_body, get_multipart_data_and_content_type, ) from httpie.utils import get_expired_cookies, repr_dict FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8' JSON_CONTENT_TYPE = 'application/json' JSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5' DEFAULT_UA = f'HTTPie/{__version__}' def collect_messages( args: argparse.Namespace, config_dir: Path, request_body_read_callback: Callable[[bytes], None] = None, ) -> Iterable[Union[requests.PreparedRequest, requests.Response]]: httpie_session = None httpie_session_headers = None if args.session or args.session_read_only: httpie_session = get_httpie_session( config_dir=config_dir, session_name=args.session or args.session_read_only, host=args.headers.get('Host'), url=args.url, ) httpie_session_headers = httpie_session.headers request_kwargs = make_request_kwargs( args=args, base_headers=httpie_session_headers, request_body_read_callback=request_body_read_callback ) send_kwargs = make_send_kwargs(args) send_kwargs_mergeable_from_env = make_send_kwargs_mergeable_from_env(args) requests_session = build_requests_session( ssl_version=args.ssl_version, ciphers=args.ciphers, verify=bool(send_kwargs_mergeable_from_env['verify']) ) if httpie_session: httpie_session.update_headers(request_kwargs['headers']) requests_session.cookies = httpie_session.cookies if args.auth_plugin: # Save auth from CLI to HTTPie session. httpie_session.auth = { 'type': args.auth_plugin.auth_type, 'raw_auth': args.auth_plugin.raw_auth, } elif httpie_session.auth: # Apply auth from HTTPie session request_kwargs['auth'] = httpie_session.auth if args.debug: # TODO: reflect the split between request and send kwargs. dump_request(request_kwargs) request = requests.Request(**request_kwargs) prepared_request = requests_session.prepare_request(request) if args.path_as_is: prepared_request.url = ensure_path_as_is( orig_url=args.url, prepped_url=prepared_request.url, ) if args.compress and prepared_request.body: compress_request( request=prepared_request, always=args.compress > 1, ) response_count = 0 expired_cookies = [] while prepared_request: yield prepared_request if not args.offline: send_kwargs_merged = requests_session.merge_environment_settings( url=prepared_request.url, **send_kwargs_mergeable_from_env, ) with max_headers(args.max_headers): response = requests_session.send( request=prepared_request, **send_kwargs_merged, **send_kwargs, ) # noinspection PyProtectedMember expired_cookies += get_expired_cookies( headers=response.raw._original_response.msg._headers ) response_count += 1 if response.next: if args.max_redirects and response_count == args.max_redirects: raise requests.TooManyRedirects if args.follow: prepared_request = response.next if args.all: yield response continue yield response break if httpie_session: if httpie_session.is_new() or not args.session_read_only: httpie_session.cookies = requests_session.cookies httpie_session.remove_cookies( # TODO: take path & domain into account? cookie['name'] for cookie in expired_cookies ) httpie_session.save()
true
2
107
httpie
httpie.client
build_requests_session
def build_requests_session( verify: bool, ssl_version: str = None, ciphers: str = None, ) -> requests.Session: requests_session = requests.Session() # Install our adapter. https_adapter = HTTPieHTTPSAdapter( ciphers=ciphers, verify=verify, ssl_version=( AVAILABLE_SSL_VERSION_ARG_MAPPING[ssl_version] if ssl_version else None ), ) requests_session.mount('https://', https_adapter) # Install adapters from plugins. for plugin_cls in plugin_manager.get_transport_plugins(): transport_plugin = plugin_cls() requests_session.mount( prefix=transport_plugin.prefix, adapter=transport_plugin.get_adapter(), ) return requests_session
[ 146, 172 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDict from httpie.plugins.registry import plugin_manager from httpie.sessions import get_httpie_session from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter from httpie.uploads import ( compress_request, prepare_request_body, get_multipart_data_and_content_type, ) from httpie.utils import get_expired_cookies, repr_dict FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8' JSON_CONTENT_TYPE = 'application/json' JSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5' DEFAULT_UA = f'HTTPie/{__version__}' def build_requests_session( verify: bool, ssl_version: str = None, ciphers: str = None, ) -> requests.Session: requests_session = requests.Session() # Install our adapter. https_adapter = HTTPieHTTPSAdapter( ciphers=ciphers, verify=verify, ssl_version=( AVAILABLE_SSL_VERSION_ARG_MAPPING[ssl_version] if ssl_version else None ), ) requests_session.mount('https://', https_adapter) # Install adapters from plugins. for plugin_cls in plugin_manager.get_transport_plugins(): transport_plugin = plugin_cls() requests_session.mount( prefix=transport_plugin.prefix, adapter=transport_plugin.get_adapter(), ) return requests_session
true
2
108
httpie
httpie.client
finalize_headers
def finalize_headers(headers: RequestHeadersDict) -> RequestHeadersDict: final_headers = RequestHeadersDict() for name, value in headers.items(): if value is not None: # “leading or trailing LWS MAY be removed without # changing the semantics of the field value” # <https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html> # Also, requests raises `InvalidHeader` for leading spaces. value = value.strip() if isinstance(value, str): # See <https://github.com/httpie/httpie/issues/212> value = value.encode('utf8') final_headers[name] = value return final_headers
[ 180, 193 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDict from httpie.plugins.registry import plugin_manager from httpie.sessions import get_httpie_session from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter from httpie.uploads import ( compress_request, prepare_request_body, get_multipart_data_and_content_type, ) from httpie.utils import get_expired_cookies, repr_dict FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8' JSON_CONTENT_TYPE = 'application/json' JSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5' DEFAULT_UA = f'HTTPie/{__version__}' def finalize_headers(headers: RequestHeadersDict) -> RequestHeadersDict: final_headers = RequestHeadersDict() for name, value in headers.items(): if value is not None: # “leading or trailing LWS MAY be removed without # changing the semantics of the field value” # <https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html> # Also, requests raises `InvalidHeader` for leading spaces. value = value.strip() if isinstance(value, str): # See <https://github.com/httpie/httpie/issues/212> value = value.encode('utf8') final_headers[name] = value return final_headers
true
2
109
httpie
httpie.client
make_default_headers
def make_default_headers(args: argparse.Namespace) -> RequestHeadersDict: default_headers = RequestHeadersDict({ 'User-Agent': DEFAULT_UA }) auto_json = args.data and not args.form if args.json or auto_json: default_headers['Accept'] = JSON_ACCEPT if args.json or (auto_json and args.data): default_headers['Content-Type'] = JSON_CONTENT_TYPE elif args.form and not args.files: # If sending files, `requests` will set # the `Content-Type` for us. default_headers['Content-Type'] = FORM_CONTENT_TYPE return default_headers
[ 196, 211 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDict from httpie.plugins.registry import plugin_manager from httpie.sessions import get_httpie_session from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter from httpie.uploads import ( compress_request, prepare_request_body, get_multipart_data_and_content_type, ) from httpie.utils import get_expired_cookies, repr_dict FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8' JSON_CONTENT_TYPE = 'application/json' JSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5' DEFAULT_UA = f'HTTPie/{__version__}' def make_default_headers(args: argparse.Namespace) -> RequestHeadersDict: default_headers = RequestHeadersDict({ 'User-Agent': DEFAULT_UA }) auto_json = args.data and not args.form if args.json or auto_json: default_headers['Accept'] = JSON_ACCEPT if args.json or (auto_json and args.data): default_headers['Content-Type'] = JSON_CONTENT_TYPE elif args.form and not args.files: # If sending files, `requests` will set # the `Content-Type` for us. default_headers['Content-Type'] = FORM_CONTENT_TYPE return default_headers
true
2
110
httpie
httpie.client
make_send_kwargs
def make_send_kwargs(args: argparse.Namespace) -> dict: kwargs = { 'timeout': args.timeout or None, 'allow_redirects': False, } return kwargs
[ 214, 219 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDict from httpie.plugins.registry import plugin_manager from httpie.sessions import get_httpie_session from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter from httpie.uploads import ( compress_request, prepare_request_body, get_multipart_data_and_content_type, ) from httpie.utils import get_expired_cookies, repr_dict FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8' JSON_CONTENT_TYPE = 'application/json' JSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5' DEFAULT_UA = f'HTTPie/{__version__}' def make_send_kwargs(args: argparse.Namespace) -> dict: kwargs = { 'timeout': args.timeout or None, 'allow_redirects': False, } return kwargs
false
0
111
httpie
httpie.client
make_send_kwargs_mergeable_from_env
def make_send_kwargs_mergeable_from_env(args: argparse.Namespace) -> dict: cert = None if args.cert: cert = args.cert if args.cert_key: cert = cert, args.cert_key kwargs = { 'proxies': {p.key: p.value for p in args.proxy}, 'stream': True, 'verify': { 'yes': True, 'true': True, 'no': False, 'false': False, }.get(args.verify.lower(), args.verify), 'cert': cert, } return kwargs
[ 222, 239 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDict from httpie.plugins.registry import plugin_manager from httpie.sessions import get_httpie_session from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter from httpie.uploads import ( compress_request, prepare_request_body, get_multipart_data_and_content_type, ) from httpie.utils import get_expired_cookies, repr_dict FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8' JSON_CONTENT_TYPE = 'application/json' JSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5' DEFAULT_UA = f'HTTPie/{__version__}' def make_send_kwargs_mergeable_from_env(args: argparse.Namespace) -> dict: cert = None if args.cert: cert = args.cert if args.cert_key: cert = cert, args.cert_key kwargs = { 'proxies': {p.key: p.value for p in args.proxy}, 'stream': True, 'verify': { 'yes': True, 'true': True, 'no': False, 'false': False, }.get(args.verify.lower(), args.verify), 'cert': cert, } return kwargs
true
2
112
httpie
httpie.client
make_request_kwargs
def make_request_kwargs( args: argparse.Namespace, base_headers: RequestHeadersDict = None, request_body_read_callback=lambda chunk: chunk ) -> dict: """ Translate our `args` into `requests.Request` keyword arguments. """ files = args.files # Serialize JSON data, if needed. data = args.data auto_json = data and not args.form if (args.json or auto_json) and isinstance(data, dict): if data: data = json.dumps(data) else: # We need to set data to an empty string to prevent requests # from assigning an empty list to `response.request.data`. data = '' # Finalize headers. headers = make_default_headers(args) if base_headers: headers.update(base_headers) headers.update(args.headers) if args.offline and args.chunked and 'Transfer-Encoding' not in headers: # When online, we let requests set the header instead to be able more # easily verify chunking is taking place. headers['Transfer-Encoding'] = 'chunked' headers = finalize_headers(headers) if (args.form and files) or args.multipart: data, headers['Content-Type'] = get_multipart_data_and_content_type( data=args.multipart_data, boundary=args.boundary, content_type=args.headers.get('Content-Type'), ) kwargs = { 'method': args.method.lower(), 'url': args.url, 'headers': headers, 'data': prepare_request_body( body=data, body_read_callback=request_body_read_callback, chunked=args.chunked, offline=args.offline, content_length_header_value=headers.get('Content-Length'), ), 'auth': args.auth, 'params': args.params.items(), } return kwargs
[ 242, 296 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDict from httpie.plugins.registry import plugin_manager from httpie.sessions import get_httpie_session from httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter from httpie.uploads import ( compress_request, prepare_request_body, get_multipart_data_and_content_type, ) from httpie.utils import get_expired_cookies, repr_dict FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8' JSON_CONTENT_TYPE = 'application/json' JSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5' DEFAULT_UA = f'HTTPie/{__version__}' def make_request_kwargs( args: argparse.Namespace, base_headers: RequestHeadersDict = None, request_body_read_callback=lambda chunk: chunk ) -> dict: """ Translate our `args` into `requests.Request` keyword arguments. """ files = args.files # Serialize JSON data, if needed. data = args.data auto_json = data and not args.form if (args.json or auto_json) and isinstance(data, dict): if data: data = json.dumps(data) else: # We need to set data to an empty string to prevent requests # from assigning an empty list to `response.request.data`. data = '' # Finalize headers. headers = make_default_headers(args) if base_headers: headers.update(base_headers) headers.update(args.headers) if args.offline and args.chunked and 'Transfer-Encoding' not in headers: # When online, we let requests set the header instead to be able more # easily verify chunking is taking place. headers['Transfer-Encoding'] = 'chunked' headers = finalize_headers(headers) if (args.form and files) or args.multipart: data, headers['Content-Type'] = get_multipart_data_and_content_type( data=args.multipart_data, boundary=args.boundary, content_type=args.headers.get('Content-Type'), ) kwargs = { 'method': args.method.lower(), 'url': args.url, 'headers': headers, 'data': prepare_request_body( body=data, body_read_callback=request_body_read_callback, chunked=args.chunked, offline=args.offline, content_length_header_value=headers.get('Content-Length'), ), 'auth': args.auth, 'params': args.params.items(), } return kwargs
true
2
113
httpie
httpie.config
get_default_config_dir
def get_default_config_dir() -> Path: """ Return the path to the httpie configuration directory. This directory isn't guaranteed to exist, and nor are any of its ancestors (only the legacy ~/.httpie, if returned, is guaranteed to exist). XDG Base Directory Specification support: <https://wiki.archlinux.org/index.php/XDG_Base_Directory> $XDG_CONFIG_HOME is supported; $XDG_CONFIG_DIRS is not """ # 1. explicitly set through env env_config_dir = os.environ.get(ENV_HTTPIE_CONFIG_DIR) if env_config_dir: return Path(env_config_dir) # 2. Windows if is_windows: return DEFAULT_WINDOWS_CONFIG_DIR home_dir = Path.home() # 3. legacy ~/.httpie legacy_config_dir = home_dir / DEFAULT_RELATIVE_LEGACY_CONFIG_DIR if legacy_config_dir.exists(): return legacy_config_dir # 4. XDG xdg_config_home_dir = os.environ.get( ENV_XDG_CONFIG_HOME, # 4.1. explicit home_dir / DEFAULT_RELATIVE_XDG_CONFIG_HOME # 4.2. default ) return Path(xdg_config_home_dir) / DEFAULT_CONFIG_DIRNAME
[ 19, 54 ]
false
[ "ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR" ]
import errno import json import os from pathlib import Path from typing import Union from httpie import __version__ from httpie.compat import is_windows ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config') DEFAULT_RELATIVE_LEGACY_CONFIG_DIR = Path('.httpie') DEFAULT_WINDOWS_CONFIG_DIR = Path( os.path.expandvars('%APPDATA%')) / DEFAULT_CONFIG_DIRNAME DEFAULT_CONFIG_DIR = get_default_config_dir() def get_default_config_dir() -> Path: """ Return the path to the httpie configuration directory. This directory isn't guaranteed to exist, and nor are any of its ancestors (only the legacy ~/.httpie, if returned, is guaranteed to exist). XDG Base Directory Specification support: <https://wiki.archlinux.org/index.php/XDG_Base_Directory> $XDG_CONFIG_HOME is supported; $XDG_CONFIG_DIRS is not """ # 1. explicitly set through env env_config_dir = os.environ.get(ENV_HTTPIE_CONFIG_DIR) if env_config_dir: return Path(env_config_dir) # 2. Windows if is_windows: return DEFAULT_WINDOWS_CONFIG_DIR home_dir = Path.home() # 3. legacy ~/.httpie legacy_config_dir = home_dir / DEFAULT_RELATIVE_LEGACY_CONFIG_DIR if legacy_config_dir.exists(): return legacy_config_dir # 4. XDG xdg_config_home_dir = os.environ.get( ENV_XDG_CONFIG_HOME, # 4.1. explicit home_dir / DEFAULT_RELATIVE_XDG_CONFIG_HOME # 4.2. default ) return Path(xdg_config_home_dir) / DEFAULT_CONFIG_DIRNAME
true
2
114
httpie
httpie.config
BaseConfigDict
ensure_directory
def ensure_directory(self): try: self.path.parent.mkdir(mode=0o700, parents=True) except OSError as e: if e.errno != errno.EEXIST: raise
[ 73, 78 ]
false
[ "ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR" ]
import errno import json import os from pathlib import Path from typing import Union from httpie import __version__ from httpie.compat import is_windows ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config') DEFAULT_RELATIVE_LEGACY_CONFIG_DIR = Path('.httpie') DEFAULT_WINDOWS_CONFIG_DIR = Path( os.path.expandvars('%APPDATA%')) / DEFAULT_CONFIG_DIRNAME DEFAULT_CONFIG_DIR = get_default_config_dir() class BaseConfigDict(dict): name = None helpurl = None about = None def __init__(self, path: Path): super().__init__() self.path = path def ensure_directory(self): try: self.path.parent.mkdir(mode=0o700, parents=True) except OSError as e: if e.errno != errno.EEXIST: raise
true
2
115
httpie
httpie.config
BaseConfigDict
load
def load(self): config_type = type(self).__name__.lower() try: with self.path.open('rt') as f: try: data = json.load(f) except ValueError as e: raise ConfigFileError( f'invalid {config_type} file: {e} [{self.path}]' ) self.update(data) except IOError as e: if e.errno != errno.ENOENT: raise ConfigFileError(f'cannot read {config_type} file: {e}')
[ 83, 96 ]
false
[ "ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR" ]
import errno import json import os from pathlib import Path from typing import Union from httpie import __version__ from httpie.compat import is_windows ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config') DEFAULT_RELATIVE_LEGACY_CONFIG_DIR = Path('.httpie') DEFAULT_WINDOWS_CONFIG_DIR = Path( os.path.expandvars('%APPDATA%')) / DEFAULT_CONFIG_DIRNAME DEFAULT_CONFIG_DIR = get_default_config_dir() class Config(BaseConfigDict): FILENAME = 'config.json' DEFAULTS = { 'default_options': [] } def __init__(self, directory: Union[str, Path] = DEFAULT_CONFIG_DIR): self.directory = Path(directory) super().__init__(path=self.directory / self.FILENAME) self.update(self.DEFAULTS) class BaseConfigDict(dict): name = None helpurl = None about = None def __init__(self, path: Path): super().__init__() self.path = path def load(self): config_type = type(self).__name__.lower() try: with self.path.open('rt') as f: try: data = json.load(f) except ValueError as e: raise ConfigFileError( f'invalid {config_type} file: {e} [{self.path}]' ) self.update(data) except IOError as e: if e.errno != errno.ENOENT: raise ConfigFileError(f'cannot read {config_type} file: {e}')
true
2
116
httpie
httpie.config
BaseConfigDict
save
def save(self, fail_silently=False): self['__meta__'] = { 'httpie': __version__ } if self.helpurl: self['__meta__']['help'] = self.helpurl if self.about: self['__meta__']['about'] = self.about self.ensure_directory() json_string = json.dumps( obj=self, indent=4, sort_keys=True, ensure_ascii=True, ) try: self.path.write_text(json_string + '\n') except IOError: if not fail_silently: raise
[ 98, 120 ]
false
[ "ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR" ]
import errno import json import os from pathlib import Path from typing import Union from httpie import __version__ from httpie.compat import is_windows ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config') DEFAULT_RELATIVE_LEGACY_CONFIG_DIR = Path('.httpie') DEFAULT_WINDOWS_CONFIG_DIR = Path( os.path.expandvars('%APPDATA%')) / DEFAULT_CONFIG_DIRNAME DEFAULT_CONFIG_DIR = get_default_config_dir() class BaseConfigDict(dict): name = None helpurl = None about = None def __init__(self, path: Path): super().__init__() self.path = path def save(self, fail_silently=False): self['__meta__'] = { 'httpie': __version__ } if self.helpurl: self['__meta__']['help'] = self.helpurl if self.about: self['__meta__']['about'] = self.about self.ensure_directory() json_string = json.dumps( obj=self, indent=4, sort_keys=True, ensure_ascii=True, ) try: self.path.write_text(json_string + '\n') except IOError: if not fail_silently: raise
true
2
117
httpie
httpie.context
Environment
__init__
def __init__(self, devnull=None, **kwargs): """ Use keyword arguments to overwrite any of the class attributes for this instance. """ assert all(hasattr(type(self), attr) for attr in kwargs.keys()) self.__dict__.update(**kwargs) # The original STDERR unaffected by --quiet’ing. self._orig_stderr = self.stderr self._devnull = devnull # Keyword arguments > stream.encoding > default utf8 if self.stdin and self.stdin_encoding is None: self.stdin_encoding = getattr( self.stdin, 'encoding', None) or 'utf8' if self.stdout_encoding is None: actual_stdout = self.stdout if is_windows: # noinspection PyUnresolvedReferences from colorama import AnsiToWin32 if isinstance(self.stdout, AnsiToWin32): # noinspection PyUnresolvedReferences actual_stdout = self.stdout.wrapped self.stdout_encoding = getattr( actual_stdout, 'encoding', None) or 'utf8'
[ 59, 84 ]
false
[]
import sys import os from pathlib import Path from typing import IO, Optional from httpie.compat import is_windows from httpie.config import DEFAULT_CONFIG_DIR, Config, ConfigFileError from httpie.utils import repr_dict class Environment: is_windows: bool = is_windows config_dir: Path = DEFAULT_CONFIG_DIR stdin: Optional[IO] = sys.stdin stdin_isatty: bool = stdin.isatty() if stdin else False stdin_encoding: str = None stdout: IO = sys.stdout stdout_isatty: bool = stdout.isatty() stdout_encoding: str = None stderr: IO = sys.stderr stderr_isatty: bool = stderr.isatty() colors = 256 program_name: str = 'http' _config: Config = None def __init__(self, devnull=None, **kwargs): """ Use keyword arguments to overwrite any of the class attributes for this instance. """ assert all(hasattr(type(self), attr) for attr in kwargs.keys()) self.__dict__.update(**kwargs) # The original STDERR unaffected by --quiet’ing. self._orig_stderr = self.stderr self._devnull = devnull # Keyword arguments > stream.encoding > default utf8 if self.stdin and self.stdin_encoding is None: self.stdin_encoding = getattr( self.stdin, 'encoding', None) or 'utf8' if self.stdout_encoding is None: actual_stdout = self.stdout if is_windows: # noinspection PyUnresolvedReferences from colorama import AnsiToWin32 if isinstance(self.stdout, AnsiToWin32): # noinspection PyUnresolvedReferences actual_stdout = self.stdout.wrapped self.stdout_encoding = getattr( actual_stdout, 'encoding', None) or 'utf8'
true
2
118
httpie
httpie.core
main
def main(args: List[Union[str, bytes]] = sys.argv, env=Environment()) -> ExitStatus: """ The main function. Pre-process args, handle some special types of invocations, and run the main program with error handling. Return exit status code. """ program_name, *args = args env.program_name = os.path.basename(program_name) args = decode_raw_args(args, env.stdin_encoding) plugin_manager.load_installed_plugins() from httpie.cli.definition import parser if env.config.default_options: args = env.config.default_options + args include_debug_info = '--debug' in args include_traceback = include_debug_info or '--traceback' in args if include_debug_info: print_debug_info(env) if args == ['--debug']: return ExitStatus.SUCCESS exit_status = ExitStatus.SUCCESS try: parsed_args = parser.parse_args( args=args, env=env, ) except KeyboardInterrupt: env.stderr.write('\n') if include_traceback: raise exit_status = ExitStatus.ERROR_CTRL_C except SystemExit as e: if e.code != ExitStatus.SUCCESS: env.stderr.write('\n') if include_traceback: raise exit_status = ExitStatus.ERROR else: try: exit_status = program( args=parsed_args, env=env, ) except KeyboardInterrupt: env.stderr.write('\n') if include_traceback: raise exit_status = ExitStatus.ERROR_CTRL_C except SystemExit as e: if e.code != ExitStatus.SUCCESS: env.stderr.write('\n') if include_traceback: raise exit_status = ExitStatus.ERROR except requests.Timeout: exit_status = ExitStatus.ERROR_TIMEOUT env.log_error(f'Request timed out ({parsed_args.timeout}s).') except requests.TooManyRedirects: exit_status = ExitStatus.ERROR_TOO_MANY_REDIRECTS env.log_error( f'Too many redirects' f' (--max-redirects={parsed_args.max_redirects}).' ) except Exception as e: # TODO: Further distinction between expected and unexpected errors. msg = str(e) if hasattr(e, 'request'): request = e.request if hasattr(request, 'url'): msg = ( f'{msg} while doing a {request.method}' f' request to URL: {request.url}' ) env.log_error(f'{type(e).__name__}: {msg}') if include_traceback: raise exit_status = ExitStatus.ERROR return exit_status
[ 21, 108 ]
false
[]
import argparse import os import platform import sys from typing import List, Optional, Tuple, Union import requests from pygments import __version__ as pygments_version from requests import __version__ as requests_version from httpie import __version__ as httpie_version from httpie.cli.constants import OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD from httpie.client import collect_messages from httpie.context import Environment from httpie.downloads import Downloader from httpie.output.writer import write_message, write_stream, MESSAGE_SEPARATOR_BYTES from httpie.plugins.registry import plugin_manager from httpie.status import ExitStatus, http_status_to_exit_status def main(args: List[Union[str, bytes]] = sys.argv, env=Environment()) -> ExitStatus: """ The main function. Pre-process args, handle some special types of invocations, and run the main program with error handling. Return exit status code. """ program_name, *args = args env.program_name = os.path.basename(program_name) args = decode_raw_args(args, env.stdin_encoding) plugin_manager.load_installed_plugins() from httpie.cli.definition import parser if env.config.default_options: args = env.config.default_options + args include_debug_info = '--debug' in args include_traceback = include_debug_info or '--traceback' in args if include_debug_info: print_debug_info(env) if args == ['--debug']: return ExitStatus.SUCCESS exit_status = ExitStatus.SUCCESS try: parsed_args = parser.parse_args( args=args, env=env, ) except KeyboardInterrupt: env.stderr.write('\n') if include_traceback: raise exit_status = ExitStatus.ERROR_CTRL_C except SystemExit as e: if e.code != ExitStatus.SUCCESS: env.stderr.write('\n') if include_traceback: raise exit_status = ExitStatus.ERROR else: try: exit_status = program( args=parsed_args, env=env, ) except KeyboardInterrupt: env.stderr.write('\n') if include_traceback: raise exit_status = ExitStatus.ERROR_CTRL_C except SystemExit as e: if e.code != ExitStatus.SUCCESS: env.stderr.write('\n') if include_traceback: raise exit_status = ExitStatus.ERROR except requests.Timeout: exit_status = ExitStatus.ERROR_TIMEOUT env.log_error(f'Request timed out ({parsed_args.timeout}s).') except requests.TooManyRedirects: exit_status = ExitStatus.ERROR_TOO_MANY_REDIRECTS env.log_error( f'Too many redirects' f' (--max-redirects={parsed_args.max_redirects}).' ) except Exception as e: # TODO: Further distinction between expected and unexpected errors. msg = str(e) if hasattr(e, 'request'): request = e.request if hasattr(request, 'url'): msg = ( f'{msg} while doing a {request.method}' f' request to URL: {request.url}' ) env.log_error(f'{type(e).__name__}: {msg}') if include_traceback: raise exit_status = ExitStatus.ERROR return exit_status
true
2
119
httpie
httpie.core
get_output_options
def get_output_options( args: argparse.Namespace, message: Union[requests.PreparedRequest, requests.Response] ) -> Tuple[bool, bool]: return { requests.PreparedRequest: ( OUT_REQ_HEAD in args.output_options, OUT_REQ_BODY in args.output_options, ), requests.Response: ( OUT_RESP_HEAD in args.output_options, OUT_RESP_BODY in args.output_options, ), }[type(message)]
[ 111, 115 ]
false
[]
import argparse import os import platform import sys from typing import List, Optional, Tuple, Union import requests from pygments import __version__ as pygments_version from requests import __version__ as requests_version from httpie import __version__ as httpie_version from httpie.cli.constants import OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD from httpie.client import collect_messages from httpie.context import Environment from httpie.downloads import Downloader from httpie.output.writer import write_message, write_stream, MESSAGE_SEPARATOR_BYTES from httpie.plugins.registry import plugin_manager from httpie.status import ExitStatus, http_status_to_exit_status def get_output_options( args: argparse.Namespace, message: Union[requests.PreparedRequest, requests.Response] ) -> Tuple[bool, bool]: return { requests.PreparedRequest: ( OUT_REQ_HEAD in args.output_options, OUT_REQ_BODY in args.output_options, ), requests.Response: ( OUT_RESP_HEAD in args.output_options, OUT_RESP_BODY in args.output_options, ), }[type(message)]
false
0
120
httpie
httpie.core
program
def program(args: argparse.Namespace, env: Environment) -> ExitStatus: """ The main program without error handling. """ # TODO: Refactor and drastically simplify, especially so that the separator logic is elsewhere. exit_status = ExitStatus.SUCCESS downloader = None initial_request: Optional[requests.PreparedRequest] = None final_response: Optional[requests.Response] = None def separate(): getattr(env.stdout, 'buffer', env.stdout).write(MESSAGE_SEPARATOR_BYTES) def request_body_read_callback(chunk: bytes): should_pipe_to_stdout = bool( # Request body output desired OUT_REQ_BODY in args.output_options # & not `.read()` already pre-request (e.g., for compression) and initial_request # & non-EOF chunk and chunk ) if should_pipe_to_stdout: msg = requests.PreparedRequest() msg.is_body_upload_chunk = True msg.body = chunk msg.headers = initial_request.headers write_message(requests_message=msg, env=env, args=args, with_body=True, with_headers=False) try: if args.download: args.follow = True # --download implies --follow. downloader = Downloader(output_file=args.output_file, progress_file=env.stderr, resume=args.download_resume) downloader.pre_request(args.headers) messages = collect_messages(args=args, config_dir=env.config.directory, request_body_read_callback=request_body_read_callback) force_separator = False prev_with_body = False # Process messages as they’re generated for message in messages: is_request = isinstance(message, requests.PreparedRequest) with_headers, with_body = get_output_options(args=args, message=message) do_write_body = with_body if prev_with_body and (with_headers or with_body) and (force_separator or not env.stdout_isatty): # Separate after a previous message with body, if needed. See test_tokens.py. separate() force_separator = False if is_request: if not initial_request: initial_request = message is_streamed_upload = not isinstance(message.body, (str, bytes)) if with_body: do_write_body = not is_streamed_upload force_separator = is_streamed_upload and env.stdout_isatty else: final_response = message if args.check_status or downloader: exit_status = http_status_to_exit_status(http_status=message.status_code, follow=args.follow) if exit_status != ExitStatus.SUCCESS and (not env.stdout_isatty or args.quiet): env.log_error(f'HTTP {message.raw.status} {message.raw.reason}', level='warning') write_message(requests_message=message, env=env, args=args, with_headers=with_headers, with_body=do_write_body) prev_with_body = with_body # Cleanup if force_separator: separate() if downloader and exit_status == ExitStatus.SUCCESS: # Last response body download. download_stream, download_to = downloader.start( initial_url=initial_request.url, final_response=final_response, ) write_stream(stream=download_stream, outfile=download_to, flush=False) downloader.finish() if downloader.interrupted: exit_status = ExitStatus.ERROR env.log_error( 'Incomplete download: size=%d; downloaded=%d' % ( downloader.status.total_size, downloader.status.downloaded )) return exit_status finally: if downloader and not downloader.finished: downloader.failed() if not isinstance(args, list) and args.output_file and args.output_file_specified: args.output_file.close()
[ 127, 217 ]
false
[]
import argparse import os import platform import sys from typing import List, Optional, Tuple, Union import requests from pygments import __version__ as pygments_version from requests import __version__ as requests_version from httpie import __version__ as httpie_version from httpie.cli.constants import OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD from httpie.client import collect_messages from httpie.context import Environment from httpie.downloads import Downloader from httpie.output.writer import write_message, write_stream, MESSAGE_SEPARATOR_BYTES from httpie.plugins.registry import plugin_manager from httpie.status import ExitStatus, http_status_to_exit_status def program(args: argparse.Namespace, env: Environment) -> ExitStatus: """ The main program without error handling. """ # TODO: Refactor and drastically simplify, especially so that the separator logic is elsewhere. exit_status = ExitStatus.SUCCESS downloader = None initial_request: Optional[requests.PreparedRequest] = None final_response: Optional[requests.Response] = None def separate(): getattr(env.stdout, 'buffer', env.stdout).write(MESSAGE_SEPARATOR_BYTES) def request_body_read_callback(chunk: bytes): should_pipe_to_stdout = bool( # Request body output desired OUT_REQ_BODY in args.output_options # & not `.read()` already pre-request (e.g., for compression) and initial_request # & non-EOF chunk and chunk ) if should_pipe_to_stdout: msg = requests.PreparedRequest() msg.is_body_upload_chunk = True msg.body = chunk msg.headers = initial_request.headers write_message(requests_message=msg, env=env, args=args, with_body=True, with_headers=False) try: if args.download: args.follow = True # --download implies --follow. downloader = Downloader(output_file=args.output_file, progress_file=env.stderr, resume=args.download_resume) downloader.pre_request(args.headers) messages = collect_messages(args=args, config_dir=env.config.directory, request_body_read_callback=request_body_read_callback) force_separator = False prev_with_body = False # Process messages as they’re generated for message in messages: is_request = isinstance(message, requests.PreparedRequest) with_headers, with_body = get_output_options(args=args, message=message) do_write_body = with_body if prev_with_body and (with_headers or with_body) and (force_separator or not env.stdout_isatty): # Separate after a previous message with body, if needed. See test_tokens.py. separate() force_separator = False if is_request: if not initial_request: initial_request = message is_streamed_upload = not isinstance(message.body, (str, bytes)) if with_body: do_write_body = not is_streamed_upload force_separator = is_streamed_upload and env.stdout_isatty else: final_response = message if args.check_status or downloader: exit_status = http_status_to_exit_status(http_status=message.status_code, follow=args.follow) if exit_status != ExitStatus.SUCCESS and (not env.stdout_isatty or args.quiet): env.log_error(f'HTTP {message.raw.status} {message.raw.reason}', level='warning') write_message(requests_message=message, env=env, args=args, with_headers=with_headers, with_body=do_write_body) prev_with_body = with_body # Cleanup if force_separator: separate() if downloader and exit_status == ExitStatus.SUCCESS: # Last response body download. download_stream, download_to = downloader.start( initial_url=initial_request.url, final_response=final_response, ) write_stream(stream=download_stream, outfile=download_to, flush=False) downloader.finish() if downloader.interrupted: exit_status = ExitStatus.ERROR env.log_error( 'Incomplete download: size=%d; downloaded=%d' % ( downloader.status.total_size, downloader.status.downloaded )) return exit_status finally: if downloader and not downloader.finished: downloader.failed() if not isinstance(args, list) and args.output_file and args.output_file_specified: args.output_file.close()
true
2
121
httpie
httpie.models
HTTPResponse
iter_lines
def iter_lines(self, chunk_size): return ((line, b'\n') for line in self._orig.iter_lines(chunk_size))
[ 48, 49 ]
false
[]
from typing import Iterable, Optional from urllib.parse import urlsplit class HTTPResponse(HTTPMessage): def iter_lines(self, chunk_size): return ((line, b'\n') for line in self._orig.iter_lines(chunk_size))
false
0
122
httpie
httpie.models
HTTPRequest
iter_body
def iter_body(self, chunk_size): yield self.body
[ 91, 92 ]
false
[]
from typing import Iterable, Optional from urllib.parse import urlsplit class HTTPRequest(HTTPMessage): def iter_body(self, chunk_size): yield self.body
false
0
123
httpie
httpie.models
HTTPRequest
iter_lines
def iter_lines(self, chunk_size): yield self.body, b''
[ 94, 95 ]
false
[]
from typing import Iterable, Optional from urllib.parse import urlsplit class HTTPRequest(HTTPMessage): def iter_lines(self, chunk_size): yield self.body, b''
false
0
124
httpie
httpie.output.formatters.colors
get_lexer
def get_lexer( mime: str, explicit_json=False, body='' ) -> Optional[Type[Lexer]]: # Build candidate mime type and lexer names. mime_types, lexer_names = [mime], [] type_, subtype = mime.split('/', 1) if '+' not in subtype: lexer_names.append(subtype) else: subtype_name, subtype_suffix = subtype.split('+', 1) lexer_names.extend([subtype_name, subtype_suffix]) mime_types.extend([ '%s/%s' % (type_, subtype_name), '%s/%s' % (type_, subtype_suffix) ]) # As a last resort, if no lexer feels responsible, and # the subtype contains 'json', take the JSON lexer if 'json' in subtype: lexer_names.append('json') # Try to resolve the right lexer. lexer = None for mime_type in mime_types: try: lexer = pygments.lexers.get_lexer_for_mimetype(mime_type) break except ClassNotFound: pass else: for name in lexer_names: try: lexer = pygments.lexers.get_lexer_by_name(name) except ClassNotFound: pass if explicit_json and body and (not lexer or isinstance(lexer, TextLexer)): # JSON response with an incorrect Content-Type? try: json.loads(body) # FIXME: the body also gets parsed in json.py except ValueError: pass # Nope else: lexer = pygments.lexers.get_lexer_by_name('json') return lexer
[ 108, 155 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from pygments.lexers.special import TextLexer from pygments.lexers.text import HttpLexer as PygmentsHttpLexer from pygments.util import ClassNotFound from httpie.compat import is_windows from httpie.context import Environment from httpie.plugins import FormatterPlugin AUTO_STYLE = 'auto' DEFAULT_STYLE = AUTO_STYLE SOLARIZED_STYLE = 'solarized' AVAILABLE_STYLES = set(pygments.styles.get_all_styles()) def get_lexer( mime: str, explicit_json=False, body='' ) -> Optional[Type[Lexer]]: # Build candidate mime type and lexer names. mime_types, lexer_names = [mime], [] type_, subtype = mime.split('/', 1) if '+' not in subtype: lexer_names.append(subtype) else: subtype_name, subtype_suffix = subtype.split('+', 1) lexer_names.extend([subtype_name, subtype_suffix]) mime_types.extend([ '%s/%s' % (type_, subtype_name), '%s/%s' % (type_, subtype_suffix) ]) # As a last resort, if no lexer feels responsible, and # the subtype contains 'json', take the JSON lexer if 'json' in subtype: lexer_names.append('json') # Try to resolve the right lexer. lexer = None for mime_type in mime_types: try: lexer = pygments.lexers.get_lexer_for_mimetype(mime_type) break except ClassNotFound: pass else: for name in lexer_names: try: lexer = pygments.lexers.get_lexer_by_name(name) except ClassNotFound: pass if explicit_json and body and (not lexer or isinstance(lexer, TextLexer)): # JSON response with an incorrect Content-Type? try: json.loads(body) # FIXME: the body also gets parsed in json.py except ValueError: pass # Nope else: lexer = pygments.lexers.get_lexer_by_name('json') return lexer
true
2
125
httpie
httpie.output.formatters.colors
ColorFormatter
__init__
def __init__( self, env: Environment, explicit_json=False, color_scheme=DEFAULT_STYLE, **kwargs ): super().__init__(**kwargs) if not env.colors: self.enabled = False return use_auto_style = color_scheme == AUTO_STYLE has_256_colors = env.colors == 256 if use_auto_style or not has_256_colors: http_lexer = PygmentsHttpLexer() formatter = TerminalFormatter() else: http_lexer = SimplifiedHTTPLexer() formatter = Terminal256Formatter( style=self.get_style_class(color_scheme) ) self.explicit_json = explicit_json # --json self.formatter = formatter self.http_lexer = http_lexer
[ 45, 71 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from pygments.lexers.special import TextLexer from pygments.lexers.text import HttpLexer as PygmentsHttpLexer from pygments.util import ClassNotFound from httpie.compat import is_windows from httpie.context import Environment from httpie.plugins import FormatterPlugin AUTO_STYLE = 'auto' DEFAULT_STYLE = AUTO_STYLE SOLARIZED_STYLE = 'solarized' AVAILABLE_STYLES = set(pygments.styles.get_all_styles()) class ColorFormatter(FormatterPlugin): group_name = 'colors' def __init__( self, env: Environment, explicit_json=False, color_scheme=DEFAULT_STYLE, **kwargs ): super().__init__(**kwargs) if not env.colors: self.enabled = False return use_auto_style = color_scheme == AUTO_STYLE has_256_colors = env.colors == 256 if use_auto_style or not has_256_colors: http_lexer = PygmentsHttpLexer() formatter = TerminalFormatter() else: http_lexer = SimplifiedHTTPLexer() formatter = Terminal256Formatter( style=self.get_style_class(color_scheme) ) self.explicit_json = explicit_json # --json self.formatter = formatter self.http_lexer = http_lexer
true
2
126
httpie
httpie.output.formatters.colors
ColorFormatter
format_headers
def format_headers(self, headers: str) -> str: return pygments.highlight( code=headers, lexer=self.http_lexer, formatter=self.formatter, ).strip()
[ 73, 74 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from pygments.lexers.special import TextLexer from pygments.lexers.text import HttpLexer as PygmentsHttpLexer from pygments.util import ClassNotFound from httpie.compat import is_windows from httpie.context import Environment from httpie.plugins import FormatterPlugin AUTO_STYLE = 'auto' DEFAULT_STYLE = AUTO_STYLE SOLARIZED_STYLE = 'solarized' AVAILABLE_STYLES = set(pygments.styles.get_all_styles()) class ColorFormatter(FormatterPlugin): group_name = 'colors' def __init__( self, env: Environment, explicit_json=False, color_scheme=DEFAULT_STYLE, **kwargs ): super().__init__(**kwargs) if not env.colors: self.enabled = False return use_auto_style = color_scheme == AUTO_STYLE has_256_colors = env.colors == 256 if use_auto_style or not has_256_colors: http_lexer = PygmentsHttpLexer() formatter = TerminalFormatter() else: http_lexer = SimplifiedHTTPLexer() formatter = Terminal256Formatter( style=self.get_style_class(color_scheme) ) self.explicit_json = explicit_json # --json self.formatter = formatter self.http_lexer = http_lexer def format_headers(self, headers: str) -> str: return pygments.highlight( code=headers, lexer=self.http_lexer, formatter=self.formatter, ).strip()
false
0
127
httpie
httpie.output.formatters.colors
ColorFormatter
format_body
def format_body(self, body: str, mime: str) -> str: lexer = self.get_lexer_for_body(mime, body) if lexer: body = pygments.highlight( code=body, lexer=lexer, formatter=self.formatter, ) return body
[ 80, 88 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from pygments.lexers.special import TextLexer from pygments.lexers.text import HttpLexer as PygmentsHttpLexer from pygments.util import ClassNotFound from httpie.compat import is_windows from httpie.context import Environment from httpie.plugins import FormatterPlugin AUTO_STYLE = 'auto' DEFAULT_STYLE = AUTO_STYLE SOLARIZED_STYLE = 'solarized' AVAILABLE_STYLES = set(pygments.styles.get_all_styles()) class ColorFormatter(FormatterPlugin): group_name = 'colors' def __init__( self, env: Environment, explicit_json=False, color_scheme=DEFAULT_STYLE, **kwargs ): super().__init__(**kwargs) if not env.colors: self.enabled = False return use_auto_style = color_scheme == AUTO_STYLE has_256_colors = env.colors == 256 if use_auto_style or not has_256_colors: http_lexer = PygmentsHttpLexer() formatter = TerminalFormatter() else: http_lexer = SimplifiedHTTPLexer() formatter = Terminal256Formatter( style=self.get_style_class(color_scheme) ) self.explicit_json = explicit_json # --json self.formatter = formatter self.http_lexer = http_lexer def format_body(self, body: str, mime: str) -> str: lexer = self.get_lexer_for_body(mime, body) if lexer: body = pygments.highlight( code=body, lexer=lexer, formatter=self.formatter, ) return body
true
2
128
httpie
httpie.output.formatters.colors
ColorFormatter
get_lexer_for_body
def get_lexer_for_body( self, mime: str, body: str ) -> Optional[Type[Lexer]]: return get_lexer( mime=mime, explicit_json=self.explicit_json, body=body, )
[ 90, 94 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from pygments.lexers.special import TextLexer from pygments.lexers.text import HttpLexer as PygmentsHttpLexer from pygments.util import ClassNotFound from httpie.compat import is_windows from httpie.context import Environment from httpie.plugins import FormatterPlugin AUTO_STYLE = 'auto' DEFAULT_STYLE = AUTO_STYLE SOLARIZED_STYLE = 'solarized' AVAILABLE_STYLES = set(pygments.styles.get_all_styles()) class ColorFormatter(FormatterPlugin): group_name = 'colors' def __init__( self, env: Environment, explicit_json=False, color_scheme=DEFAULT_STYLE, **kwargs ): super().__init__(**kwargs) if not env.colors: self.enabled = False return use_auto_style = color_scheme == AUTO_STYLE has_256_colors = env.colors == 256 if use_auto_style or not has_256_colors: http_lexer = PygmentsHttpLexer() formatter = TerminalFormatter() else: http_lexer = SimplifiedHTTPLexer() formatter = Terminal256Formatter( style=self.get_style_class(color_scheme) ) self.explicit_json = explicit_json # --json self.formatter = formatter self.http_lexer = http_lexer def get_lexer_for_body( self, mime: str, body: str ) -> Optional[Type[Lexer]]: return get_lexer( mime=mime, explicit_json=self.explicit_json, body=body, )
false
0
129
httpie
httpie.output.formatters.colors
ColorFormatter
get_style_class
@staticmethod def get_style_class(color_scheme: str) -> Type[pygments.style.Style]: try: return pygments.styles.get_style_by_name(color_scheme) except ClassNotFound: return Solarized256Style
[ 101, 105 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from pygments.lexers.special import TextLexer from pygments.lexers.text import HttpLexer as PygmentsHttpLexer from pygments.util import ClassNotFound from httpie.compat import is_windows from httpie.context import Environment from httpie.plugins import FormatterPlugin AUTO_STYLE = 'auto' DEFAULT_STYLE = AUTO_STYLE SOLARIZED_STYLE = 'solarized' AVAILABLE_STYLES = set(pygments.styles.get_all_styles()) class ColorFormatter(FormatterPlugin): group_name = 'colors' def __init__( self, env: Environment, explicit_json=False, color_scheme=DEFAULT_STYLE, **kwargs ): super().__init__(**kwargs) if not env.colors: self.enabled = False return use_auto_style = color_scheme == AUTO_STYLE has_256_colors = env.colors == 256 if use_auto_style or not has_256_colors: http_lexer = PygmentsHttpLexer() formatter = TerminalFormatter() else: http_lexer = SimplifiedHTTPLexer() formatter = Terminal256Formatter( style=self.get_style_class(color_scheme) ) self.explicit_json = explicit_json # --json self.formatter = formatter self.http_lexer = http_lexer @staticmethod def get_style_class(color_scheme: str) -> Type[pygments.style.Style]: try: return pygments.styles.get_style_by_name(color_scheme) except ClassNotFound: return Solarized256Style
false
0
130
httpie
httpie.output.formatters.headers
HeadersFormatter
__init__
def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['headers']['sort']
[ 5, 7 ]
false
[]
from httpie.plugins import FormatterPlugin class HeadersFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['headers']['sort']
false
0
131
httpie
httpie.output.formatters.headers
HeadersFormatter
format_headers
def format_headers(self, headers: str) -> str: """ Sorts headers by name while retaining relative order of multiple headers with the same name. """ lines = headers.splitlines() headers = sorted(lines[1:], key=lambda h: h.split(':')[0]) return '\r\n'.join(lines[:1] + headers)
[ 9, 17 ]
false
[]
from httpie.plugins import FormatterPlugin class HeadersFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['headers']['sort'] def format_headers(self, headers: str) -> str: """ Sorts headers by name while retaining relative order of multiple headers with the same name. """ lines = headers.splitlines() headers = sorted(lines[1:], key=lambda h: h.split(':')[0]) return '\r\n'.join(lines[:1] + headers)
false
0
132
httpie
httpie.output.formatters.json
JSONFormatter
__init__
def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['json']['format']
[ 8, 10 ]
false
[]
import json from httpie.plugins import FormatterPlugin class JSONFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['json']['format']
false
0
133
httpie
httpie.output.formatters.json
JSONFormatter
format_body
def format_body(self, body: str, mime: str) -> str: maybe_json = [ 'json', 'javascript', 'text', ] if (self.kwargs['explicit_json'] or any(token in mime for token in maybe_json)): try: obj = json.loads(body) except ValueError: pass # Invalid JSON, ignore. else: # Indent, sort keys by name, and avoid # unicode escapes to improve readability. body = json.dumps( obj=obj, sort_keys=self.format_options['json']['sort_keys'], ensure_ascii=False, indent=self.format_options['json']['indent'] ) return body
[ 12, 33 ]
false
[]
import json from httpie.plugins import FormatterPlugin class JSONFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['json']['format'] def format_body(self, body: str, mime: str) -> str: maybe_json = [ 'json', 'javascript', 'text', ] if (self.kwargs['explicit_json'] or any(token in mime for token in maybe_json)): try: obj = json.loads(body) except ValueError: pass # Invalid JSON, ignore. else: # Indent, sort keys by name, and avoid # unicode escapes to improve readability. body = json.dumps( obj=obj, sort_keys=self.format_options['json']['sort_keys'], ensure_ascii=False, indent=self.format_options['json']['indent'] ) return body
true
2
134
httpie
httpie.output.processing
Conversion
get_converter
@staticmethod def get_converter(mime: str) -> Optional[ConverterPlugin]: if is_valid_mime(mime): for converter_class in plugin_manager.get_converters(): if converter_class.supports(mime): return converter_class(mime)
[ 18, 22 ]
false
[ "MIME_RE" ]
import re from typing import Optional, List from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from httpie.context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') class Conversion: @staticmethod def get_converter(mime: str) -> Optional[ConverterPlugin]: if is_valid_mime(mime): for converter_class in plugin_manager.get_converters(): if converter_class.supports(mime): return converter_class(mime)
true
2
135
httpie
httpie.output.processing
Formatting
__init__
def __init__(self, groups: List[str], env=Environment(), **kwargs): """ :param groups: names of processor groups to be applied :param env: Environment :param kwargs: additional keyword arguments for processors """ available_plugins = plugin_manager.get_formatters_grouped() self.enabled_plugins = [] for group in groups: for cls in available_plugins[group]: p = cls(env=env, **kwargs) if p.enabled: self.enabled_plugins.append(p)
[ 28, 41 ]
false
[ "MIME_RE" ]
import re from typing import Optional, List from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from httpie.context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') class Formatting: def __init__(self, groups: List[str], env=Environment(), **kwargs): """ :param groups: names of processor groups to be applied :param env: Environment :param kwargs: additional keyword arguments for processors """ available_plugins = plugin_manager.get_formatters_grouped() self.enabled_plugins = [] for group in groups: for cls in available_plugins[group]: p = cls(env=env, **kwargs) if p.enabled: self.enabled_plugins.append(p)
true
2
136
httpie
httpie.output.processing
Formatting
format_headers
def format_headers(self, headers: str) -> str: for p in self.enabled_plugins: headers = p.format_headers(headers) return headers
[ 43, 46 ]
false
[ "MIME_RE" ]
import re from typing import Optional, List from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from httpie.context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') class Formatting: def __init__(self, groups: List[str], env=Environment(), **kwargs): """ :param groups: names of processor groups to be applied :param env: Environment :param kwargs: additional keyword arguments for processors """ available_plugins = plugin_manager.get_formatters_grouped() self.enabled_plugins = [] for group in groups: for cls in available_plugins[group]: p = cls(env=env, **kwargs) if p.enabled: self.enabled_plugins.append(p) def format_headers(self, headers: str) -> str: for p in self.enabled_plugins: headers = p.format_headers(headers) return headers
true
2
137
httpie
httpie.output.processing
Formatting
format_body
def format_body(self, content: str, mime: str) -> str: if is_valid_mime(mime): for p in self.enabled_plugins: content = p.format_body(content, mime) return content
[ 48, 52 ]
false
[ "MIME_RE" ]
import re from typing import Optional, List from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from httpie.context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') class Formatting: def __init__(self, groups: List[str], env=Environment(), **kwargs): """ :param groups: names of processor groups to be applied :param env: Environment :param kwargs: additional keyword arguments for processors """ available_plugins = plugin_manager.get_formatters_grouped() self.enabled_plugins = [] for group in groups: for cls in available_plugins[group]: p = cls(env=env, **kwargs) if p.enabled: self.enabled_plugins.append(p) def format_body(self, content: str, mime: str) -> str: if is_valid_mime(mime): for p in self.enabled_plugins: content = p.format_body(content, mime) return content
true
2
138
httpie
httpie.output.streams
BaseStream
__init__
def __init__( self, msg: HTTPMessage, with_headers=True, with_body=True, on_body_chunk_downloaded: Callable[[bytes], None] = None ): """ :param msg: a :class:`models.HTTPMessage` subclass :param with_headers: if `True`, headers will be included :param with_body: if `True`, body will be included """ assert with_headers or with_body self.msg = msg self.with_headers = with_headers self.with_body = with_body self.on_body_chunk_downloaded = on_body_chunk_downloaded
[ 29, 46 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class BaseStream: def __init__( self, msg: HTTPMessage, with_headers=True, with_body=True, on_body_chunk_downloaded: Callable[[bytes], None] = None ): """ :param msg: a :class:`models.HTTPMessage` subclass :param with_headers: if `True`, headers will be included :param with_body: if `True`, body will be included """ assert with_headers or with_body self.msg = msg self.with_headers = with_headers self.with_body = with_body self.on_body_chunk_downloaded = on_body_chunk_downloaded
false
0
139
httpie
httpie.output.streams
BaseStream
__iter__
def __iter__(self) -> Iterable[bytes]: """Return an iterator over `self.msg`.""" if self.with_headers: yield self.get_headers() yield b'\r\n\r\n' if self.with_body: try: for chunk in self.iter_body(): yield chunk if self.on_body_chunk_downloaded: self.on_body_chunk_downloaded(chunk) except DataSuppressedError as e: if self.with_headers: yield b'\n' yield e.message
[ 56, 71 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class BaseStream: def __init__( self, msg: HTTPMessage, with_headers=True, with_body=True, on_body_chunk_downloaded: Callable[[bytes], None] = None ): """ :param msg: a :class:`models.HTTPMessage` subclass :param with_headers: if `True`, headers will be included :param with_body: if `True`, body will be included """ assert with_headers or with_body self.msg = msg self.with_headers = with_headers self.with_body = with_body self.on_body_chunk_downloaded = on_body_chunk_downloaded def __iter__(self) -> Iterable[bytes]: """Return an iterator over `self.msg`.""" if self.with_headers: yield self.get_headers() yield b'\r\n\r\n' if self.with_body: try: for chunk in self.iter_body(): yield chunk if self.on_body_chunk_downloaded: self.on_body_chunk_downloaded(chunk) except DataSuppressedError as e: if self.with_headers: yield b'\n' yield e.message
true
2
140
httpie
httpie.output.streams
RawStream
__init__
def __init__(self, chunk_size=CHUNK_SIZE, **kwargs): super().__init__(**kwargs) self.chunk_size = chunk_size
[ 80, 82 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class RawStream(BaseStream): CHUNK_SIZE = 1024 * 100 CHUNK_SIZE_BY_LINE = 1 def __init__(self, chunk_size=CHUNK_SIZE, **kwargs): super().__init__(**kwargs) self.chunk_size = chunk_size
false
0
141
httpie
httpie.output.streams
RawStream
iter_body
def iter_body(self) -> Iterable[bytes]: return self.msg.iter_body(self.chunk_size)
[ 84, 85 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class RawStream(BaseStream): CHUNK_SIZE = 1024 * 100 CHUNK_SIZE_BY_LINE = 1 def __init__(self, chunk_size=CHUNK_SIZE, **kwargs): super().__init__(**kwargs) self.chunk_size = chunk_size def iter_body(self) -> Iterable[bytes]: return self.msg.iter_body(self.chunk_size)
false
0
142
httpie
httpie.output.streams
EncodedStream
__init__
def __init__(self, env=Environment(), **kwargs): super().__init__(**kwargs) if env.stdout_isatty: # Use the encoding supported by the terminal. output_encoding = env.stdout_encoding else: # Preserve the message encoding. output_encoding = self.msg.encoding # Default to utf8 when unsure. self.output_encoding = output_encoding or 'utf8'
[ 98, 107 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class EncodedStream(BaseStream): CHUNK_SIZE = 1 def __init__(self, env=Environment(), **kwargs): super().__init__(**kwargs) if env.stdout_isatty: # Use the encoding supported by the terminal. output_encoding = env.stdout_encoding else: # Preserve the message encoding. output_encoding = self.msg.encoding # Default to utf8 when unsure. self.output_encoding = output_encoding or 'utf8'
true
2
143
httpie
httpie.output.streams
EncodedStream
iter_body
def iter_body(self) -> Iterable[bytes]: for line, lf in self.msg.iter_lines(self.CHUNK_SIZE): if b'\0' in line: raise BinarySuppressedError() yield line.decode(self.msg.encoding) \ .encode(self.output_encoding, 'replace') + lf
[ 109, 113 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class EncodedStream(BaseStream): CHUNK_SIZE = 1 def __init__(self, env=Environment(), **kwargs): super().__init__(**kwargs) if env.stdout_isatty: # Use the encoding supported by the terminal. output_encoding = env.stdout_encoding else: # Preserve the message encoding. output_encoding = self.msg.encoding # Default to utf8 when unsure. self.output_encoding = output_encoding or 'utf8' def iter_body(self) -> Iterable[bytes]: for line, lf in self.msg.iter_lines(self.CHUNK_SIZE): if b'\0' in line: raise BinarySuppressedError() yield line.decode(self.msg.encoding) \ .encode(self.output_encoding, 'replace') + lf
true
2
144
httpie
httpie.output.streams
PrettyStream
__init__
def __init__( self, conversion: Conversion, formatting: Formatting, **kwargs, ): super().__init__(**kwargs) self.formatting = formatting self.conversion = conversion self.mime = self.msg.content_type.split(';')[0]
[ 128, 136 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class PrettyStream(EncodedStream): CHUNK_SIZE = 1 def __init__( self, conversion: Conversion, formatting: Formatting, **kwargs, ): super().__init__(**kwargs) self.formatting = formatting self.conversion = conversion self.mime = self.msg.content_type.split(';')[0]
false
0
145
httpie
httpie.output.streams
PrettyStream
get_headers
def get_headers(self) -> bytes: return self.formatting.format_headers( self.msg.headers).encode(self.output_encoding)
[ 138, 139 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class PrettyStream(EncodedStream): CHUNK_SIZE = 1 def __init__( self, conversion: Conversion, formatting: Formatting, **kwargs, ): super().__init__(**kwargs) self.formatting = formatting self.conversion = conversion self.mime = self.msg.content_type.split(';')[0] def get_headers(self) -> bytes: return self.formatting.format_headers( self.msg.headers).encode(self.output_encoding)
false
0
146
httpie
httpie.output.streams
PrettyStream
iter_body
def iter_body(self) -> Iterable[bytes]: first_chunk = True iter_lines = self.msg.iter_lines(self.CHUNK_SIZE) for line, lf in iter_lines: if b'\0' in line: if first_chunk: converter = self.conversion.get_converter(self.mime) if converter: body = bytearray() # noinspection PyAssignmentToLoopOrWithParameter for line, lf in chain([(line, lf)], iter_lines): body.extend(line) body.extend(lf) self.mime, body = converter.convert(body) assert isinstance(body, str) yield self.process_body(body) return raise BinarySuppressedError() yield self.process_body(line) + lf first_chunk = False
[ 142, 161 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class PrettyStream(EncodedStream): CHUNK_SIZE = 1 def __init__( self, conversion: Conversion, formatting: Formatting, **kwargs, ): super().__init__(**kwargs) self.formatting = formatting self.conversion = conversion self.mime = self.msg.content_type.split(';')[0] def iter_body(self) -> Iterable[bytes]: first_chunk = True iter_lines = self.msg.iter_lines(self.CHUNK_SIZE) for line, lf in iter_lines: if b'\0' in line: if first_chunk: converter = self.conversion.get_converter(self.mime) if converter: body = bytearray() # noinspection PyAssignmentToLoopOrWithParameter for line, lf in chain([(line, lf)], iter_lines): body.extend(line) body.extend(lf) self.mime, body = converter.convert(body) assert isinstance(body, str) yield self.process_body(body) return raise BinarySuppressedError() yield self.process_body(line) + lf first_chunk = False
true
2
147
httpie
httpie.output.streams
PrettyStream
process_body
def process_body(self, chunk: Union[str, bytes]) -> bytes: if not isinstance(chunk, str): # Text when a converter has been used, # otherwise it will always be bytes. chunk = chunk.decode(self.msg.encoding, 'replace') chunk = self.formatting.format_body(content=chunk, mime=self.mime) return chunk.encode(self.output_encoding, 'replace')
[ 163, 169 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class PrettyStream(EncodedStream): CHUNK_SIZE = 1 def __init__( self, conversion: Conversion, formatting: Formatting, **kwargs, ): super().__init__(**kwargs) self.formatting = formatting self.conversion = conversion self.mime = self.msg.content_type.split(';')[0] def process_body(self, chunk: Union[str, bytes]) -> bytes: if not isinstance(chunk, str): # Text when a converter has been used, # otherwise it will always be bytes. chunk = chunk.decode(self.msg.encoding, 'replace') chunk = self.formatting.format_body(content=chunk, mime=self.mime) return chunk.encode(self.output_encoding, 'replace')
true
2
148
httpie
httpie.output.streams
BufferedPrettyStream
iter_body
def iter_body(self) -> Iterable[bytes]: # Read the whole body before prettifying it, # but bail out immediately if the body is binary. converter = None body = bytearray() for chunk in self.msg.iter_body(self.CHUNK_SIZE): if not converter and b'\0' in chunk: converter = self.conversion.get_converter(self.mime) if not converter: raise BinarySuppressedError() body.extend(chunk) if converter: self.mime, body = converter.convert(body) yield self.process_body(body)
[ 182, 198 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: binary data not shown in terminal |\n' b'+-----------------------------------------+' ) class BufferedPrettyStream(PrettyStream): CHUNK_SIZE = 1024 * 10 def iter_body(self) -> Iterable[bytes]: # Read the whole body before prettifying it, # but bail out immediately if the body is binary. converter = None body = bytearray() for chunk in self.msg.iter_body(self.CHUNK_SIZE): if not converter and b'\0' in chunk: converter = self.conversion.get_converter(self.mime) if not converter: raise BinarySuppressedError() body.extend(chunk) if converter: self.mime, body = converter.convert(body) yield self.process_body(body)
true
2
149
httpie
httpie.output.writer
write_message
def write_message( requests_message: Union[requests.PreparedRequest, requests.Response], env: Environment, args: argparse.Namespace, with_headers=False, with_body=False, ): if not (with_body or with_headers): return write_stream_kwargs = { 'stream': build_output_stream_for_message( args=args, env=env, requests_message=requests_message, with_body=with_body, with_headers=with_headers, ), # NOTE: `env.stdout` will in fact be `stderr` with `--download` 'outfile': env.stdout, 'flush': env.stdout_isatty or args.stream } try: if env.is_windows and 'colors' in args.prettify: write_stream_with_colors_win_py3(**write_stream_kwargs) else: write_stream(**write_stream_kwargs) except IOError as e: show_traceback = args.debug or args.traceback if not show_traceback and e.errno == errno.EPIPE: # Ignore broken pipes unless --traceback. env.stderr.write('\n') else: raise
[ 18, 50 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream, ) MESSAGE_SEPARATOR = '\n\n' MESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode() def write_message( requests_message: Union[requests.PreparedRequest, requests.Response], env: Environment, args: argparse.Namespace, with_headers=False, with_body=False, ): if not (with_body or with_headers): return write_stream_kwargs = { 'stream': build_output_stream_for_message( args=args, env=env, requests_message=requests_message, with_body=with_body, with_headers=with_headers, ), # NOTE: `env.stdout` will in fact be `stderr` with `--download` 'outfile': env.stdout, 'flush': env.stdout_isatty or args.stream } try: if env.is_windows and 'colors' in args.prettify: write_stream_with_colors_win_py3(**write_stream_kwargs) else: write_stream(**write_stream_kwargs) except IOError as e: show_traceback = args.debug or args.traceback if not show_traceback and e.errno == errno.EPIPE: # Ignore broken pipes unless --traceback. env.stderr.write('\n') else: raise
true
2
150
httpie
httpie.output.writer
write_stream
def write_stream( stream: BaseStream, outfile: Union[IO, TextIO], flush: bool ): """Write the output stream.""" try: # Writing bytes so we use the buffer interface (Python 3). buf = outfile.buffer except AttributeError: buf = outfile for chunk in stream: buf.write(chunk) if flush: outfile.flush()
[ 53, 68 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream, ) MESSAGE_SEPARATOR = '\n\n' MESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode() def write_stream( stream: BaseStream, outfile: Union[IO, TextIO], flush: bool ): """Write the output stream.""" try: # Writing bytes so we use the buffer interface (Python 3). buf = outfile.buffer except AttributeError: buf = outfile for chunk in stream: buf.write(chunk) if flush: outfile.flush()
true
2
151
httpie
httpie.output.writer
write_stream_with_colors_win_py3
def write_stream_with_colors_win_py3( stream: 'BaseStream', outfile: TextIO, flush: bool ): """Like `write`, but colorized chunks are written as text directly to `outfile` to ensure it gets processed by colorama. Applies only to Windows with Python 3 and colorized terminal output. """ color = b'\x1b[' encoding = outfile.encoding for chunk in stream: if color in chunk: outfile.write(chunk.decode(encoding)) else: outfile.buffer.write(chunk) if flush: outfile.flush()
[ 71, 89 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream, ) MESSAGE_SEPARATOR = '\n\n' MESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode() def write_stream_with_colors_win_py3( stream: 'BaseStream', outfile: TextIO, flush: bool ): """Like `write`, but colorized chunks are written as text directly to `outfile` to ensure it gets processed by colorama. Applies only to Windows with Python 3 and colorized terminal output. """ color = b'\x1b[' encoding = outfile.encoding for chunk in stream: if color in chunk: outfile.write(chunk.decode(encoding)) else: outfile.buffer.write(chunk) if flush: outfile.flush()
true
2
152
httpie
httpie.output.writer
build_output_stream_for_message
def build_output_stream_for_message( args: argparse.Namespace, env: Environment, requests_message: Union[requests.PreparedRequest, requests.Response], with_headers: bool, with_body: bool, ): stream_class, stream_kwargs = get_stream_type_and_kwargs( env=env, args=args, ) message_class = { requests.PreparedRequest: HTTPRequest, requests.Response: HTTPResponse, }[type(requests_message)] yield from stream_class( msg=message_class(requests_message), with_headers=with_headers, with_body=with_body, **stream_kwargs, ) if (env.stdout_isatty and with_body and not getattr(requests_message, 'is_body_upload_chunk', False)): # Ensure a blank line after the response body. # For terminal output only. yield MESSAGE_SEPARATOR_BYTES
[ 92, 117 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream, ) MESSAGE_SEPARATOR = '\n\n' MESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode() def build_output_stream_for_message( args: argparse.Namespace, env: Environment, requests_message: Union[requests.PreparedRequest, requests.Response], with_headers: bool, with_body: bool, ): stream_class, stream_kwargs = get_stream_type_and_kwargs( env=env, args=args, ) message_class = { requests.PreparedRequest: HTTPRequest, requests.Response: HTTPResponse, }[type(requests_message)] yield from stream_class( msg=message_class(requests_message), with_headers=with_headers, with_body=with_body, **stream_kwargs, ) if (env.stdout_isatty and with_body and not getattr(requests_message, 'is_body_upload_chunk', False)): # Ensure a blank line after the response body. # For terminal output only. yield MESSAGE_SEPARATOR_BYTES
true
2
153
httpie
httpie.output.writer
get_stream_type_and_kwargs
def get_stream_type_and_kwargs( env: Environment, args: argparse.Namespace ) -> Tuple[Type['BaseStream'], dict]: """Pick the right stream type and kwargs for it based on `env` and `args`. """ if not env.stdout_isatty and not args.prettify: stream_class = RawStream stream_kwargs = { 'chunk_size': ( RawStream.CHUNK_SIZE_BY_LINE if args.stream else RawStream.CHUNK_SIZE ) } elif args.prettify: stream_class = PrettyStream if args.stream else BufferedPrettyStream stream_kwargs = { 'env': env, 'conversion': Conversion(), 'formatting': Formatting( env=env, groups=args.prettify, color_scheme=args.style, explicit_json=args.json, format_options=args.format_options, ) } else: stream_class = EncodedStream stream_kwargs = { 'env': env } return stream_class, stream_kwargs
[ 120, 155 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream, ) MESSAGE_SEPARATOR = '\n\n' MESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode() def get_stream_type_and_kwargs( env: Environment, args: argparse.Namespace ) -> Tuple[Type['BaseStream'], dict]: """Pick the right stream type and kwargs for it based on `env` and `args`. """ if not env.stdout_isatty and not args.prettify: stream_class = RawStream stream_kwargs = { 'chunk_size': ( RawStream.CHUNK_SIZE_BY_LINE if args.stream else RawStream.CHUNK_SIZE ) } elif args.prettify: stream_class = PrettyStream if args.stream else BufferedPrettyStream stream_kwargs = { 'env': env, 'conversion': Conversion(), 'formatting': Formatting( env=env, groups=args.prettify, color_scheme=args.style, explicit_json=args.json, format_options=args.format_options, ) } else: stream_class = EncodedStream stream_kwargs = { 'env': env } return stream_class, stream_kwargs
true
2
154
httpie
httpie.plugins.base
AuthPlugin
get_auth
def get_auth(self, username=None, password=None): """ If `auth_parse` is set to `True`, then `username` and `password` contain the parsed credentials. Use `self.raw_auth` to access the raw value passed through `--auth, -a`. Return a ``requests.auth.AuthBase`` subclass instance. """ raise NotImplementedError()
[ 55, 66 ]
false
[]
class AuthPlugin(BasePlugin): auth_type = None auth_require = True auth_parse = True netrc_parse = False prompt_password = True raw_auth = None def get_auth(self, username=None, password=None): """ If `auth_parse` is set to `True`, then `username` and `password` contain the parsed credentials. Use `self.raw_auth` to access the raw value passed through `--auth, -a`. Return a ``requests.auth.AuthBase`` subclass instance. """ raise NotImplementedError()
false
0
155
httpie
httpie.plugins.base
TransportPlugin
get_adapter
def get_adapter(self): """ Return a ``requests.adapters.BaseAdapter`` subclass instance to be mounted to ``self.prefix``. """ raise NotImplementedError()
[ 84, 90 ]
false
[]
class TransportPlugin(BasePlugin): prefix = None def get_adapter(self): """ Return a ``requests.adapters.BaseAdapter`` subclass instance to be mounted to ``self.prefix``. """ raise NotImplementedError()
false
0
156
httpie
httpie.plugins.base
ConverterPlugin
__init__
def __init__(self, mime): self.mime = mime
[ 103, 104 ]
false
[]
class ConverterPlugin(BasePlugin): def __init__(self, mime): self.mime = mime
false
0
157
httpie
httpie.plugins.base
ConverterPlugin
convert
def convert(self, content_bytes): raise NotImplementedError
[ 106, 107 ]
false
[]
class ConverterPlugin(BasePlugin): def __init__(self, mime): self.mime = mime def convert(self, content_bytes): raise NotImplementedError
false
0
158
httpie
httpie.plugins.base
FormatterPlugin
__init__
def __init__(self, **kwargs): """ :param env: an class:`Environment` instance :param kwargs: additional keyword argument that some formatters might require. """ self.enabled = True self.kwargs = kwargs self.format_options = kwargs['format_options']
[ 121, 130 ]
false
[]
class FormatterPlugin(BasePlugin): group_name = 'format' def __init__(self, **kwargs): """ :param env: an class:`Environment` instance :param kwargs: additional keyword argument that some formatters might require. """ self.enabled = True self.kwargs = kwargs self.format_options = kwargs['format_options']
false
0
159
httpie
httpie.plugins.base
FormatterPlugin
format_headers
def format_headers(self, headers: str) -> str: """Return processed `headers` :param headers: The headers as text. """ return headers
[ 132, 138 ]
false
[]
class FormatterPlugin(BasePlugin): group_name = 'format' def __init__(self, **kwargs): """ :param env: an class:`Environment` instance :param kwargs: additional keyword argument that some formatters might require. """ self.enabled = True self.kwargs = kwargs self.format_options = kwargs['format_options'] def format_headers(self, headers: str) -> str: """Return processed `headers` :param headers: The headers as text. """ return headers
false
0
160
httpie
httpie.plugins.base
FormatterPlugin
format_body
def format_body(self, content: str, mime: str) -> str: """Return processed `content`. :param mime: E.g., 'application/atom+xml'. :param content: The body content as text """ return content
[ 140, 147 ]
false
[]
class FormatterPlugin(BasePlugin): group_name = 'format' def __init__(self, **kwargs): """ :param env: an class:`Environment` instance :param kwargs: additional keyword argument that some formatters might require. """ self.enabled = True self.kwargs = kwargs self.format_options = kwargs['format_options'] def format_body(self, content: str, mime: str) -> str: """Return processed `content`. :param mime: E.g., 'application/atom+xml'. :param content: The body content as text """ return content
false
0
161
httpie
httpie.plugins.manager
PluginManager
filter
def filter(self, by_type=Type[BasePlugin]): return [plugin for plugin in self if issubclass(plugin, by_type)]
[ 27, 28 ]
false
[ "ENTRY_POINT_NAMES" ]
from itertools import groupby from operator import attrgetter from typing import Dict, List, Type from pkg_resources import iter_entry_points from httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin from httpie.plugins.base import BasePlugin, TransportPlugin ENTRY_POINT_NAMES = [ 'httpie.plugins.auth.v1', 'httpie.plugins.formatter.v1', 'httpie.plugins.converter.v1', 'httpie.plugins.transport.v1', ] class PluginManager(list): def filter(self, by_type=Type[BasePlugin]): return [plugin for plugin in self if issubclass(plugin, by_type)]
false
0
162
httpie
httpie.plugins.manager
PluginManager
load_installed_plugins
def load_installed_plugins(self): for entry_point_name in ENTRY_POINT_NAMES: for entry_point in iter_entry_points(entry_point_name): plugin = entry_point.load() plugin.package_name = entry_point.dist.key self.register(entry_point.load())
[ 30, 35 ]
false
[ "ENTRY_POINT_NAMES" ]
from itertools import groupby from operator import attrgetter from typing import Dict, List, Type from pkg_resources import iter_entry_points from httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin from httpie.plugins.base import BasePlugin, TransportPlugin ENTRY_POINT_NAMES = [ 'httpie.plugins.auth.v1', 'httpie.plugins.formatter.v1', 'httpie.plugins.converter.v1', 'httpie.plugins.transport.v1', ] class PluginManager(list): def load_installed_plugins(self): for entry_point_name in ENTRY_POINT_NAMES: for entry_point in iter_entry_points(entry_point_name): plugin = entry_point.load() plugin.package_name = entry_point.dist.key self.register(entry_point.load())
true
2
163
httpie
httpie.plugins.manager
PluginManager
get_auth_plugin_mapping
def get_auth_plugin_mapping(self) -> Dict[str, Type[AuthPlugin]]: return { plugin.auth_type: plugin for plugin in self.get_auth_plugins() }
[ 41, 42 ]
false
[ "ENTRY_POINT_NAMES" ]
from itertools import groupby from operator import attrgetter from typing import Dict, List, Type from pkg_resources import iter_entry_points from httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin from httpie.plugins.base import BasePlugin, TransportPlugin ENTRY_POINT_NAMES = [ 'httpie.plugins.auth.v1', 'httpie.plugins.formatter.v1', 'httpie.plugins.converter.v1', 'httpie.plugins.transport.v1', ] class PluginManager(list): def get_auth_plugin_mapping(self) -> Dict[str, Type[AuthPlugin]]: return { plugin.auth_type: plugin for plugin in self.get_auth_plugins() }
false
0
164
httpie
httpie.plugins.manager
PluginManager
get_formatters_grouped
def get_formatters_grouped(self) -> Dict[str, List[Type[FormatterPlugin]]]: return { group_name: list(group) for group_name, group in groupby(self.get_formatters(), key=attrgetter('group_name')) }
[ 53, 54 ]
false
[ "ENTRY_POINT_NAMES" ]
from itertools import groupby from operator import attrgetter from typing import Dict, List, Type from pkg_resources import iter_entry_points from httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin from httpie.plugins.base import BasePlugin, TransportPlugin ENTRY_POINT_NAMES = [ 'httpie.plugins.auth.v1', 'httpie.plugins.formatter.v1', 'httpie.plugins.converter.v1', 'httpie.plugins.transport.v1', ] class PluginManager(list): def get_formatters_grouped(self) -> Dict[str, List[Type[FormatterPlugin]]]: return { group_name: list(group) for group_name, group in groupby(self.get_formatters(), key=attrgetter('group_name')) }
false
0
165
httpie
httpie.sessions
get_httpie_session
def get_httpie_session( config_dir: Path, session_name: str, host: Optional[str], url: str, ) -> 'Session': if os.path.sep in session_name: path = os.path.expanduser(session_name) else: hostname = host or urlsplit(url).netloc.split('@')[-1] if not hostname: # HACK/FIXME: httpie-unixsocket's URLs have no hostname. hostname = 'localhost' # host:port => host_port hostname = hostname.replace(':', '_') path = ( config_dir / SESSIONS_DIR_NAME / hostname / f'{session_name}.json' ) session = Session(path) session.load() return session
[ 29, 50 ]
false
[ "SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES" ]
import os import re from http.cookies import SimpleCookie from pathlib import Path from typing import Iterable, Optional, Union from urllib.parse import urlsplit from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, create_cookie from httpie.cli.dicts import RequestHeadersDict from httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR from httpie.plugins.registry import plugin_manager SESSIONS_DIR_NAME = 'sessions' DEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME VALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$') SESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-'] class Session(BaseConfigDict): helpurl = 'https://httpie.org/doc#sessions' about = 'HTTPie session file' def __init__(self, path: Union[str, Path]): super().__init__(path=Path(path)) self['headers'] = {} self['cookies'] = {} self['auth'] = { 'type': None, 'username': None, 'password': None } def get_httpie_session( config_dir: Path, session_name: str, host: Optional[str], url: str, ) -> 'Session': if os.path.sep in session_name: path = os.path.expanduser(session_name) else: hostname = host or urlsplit(url).netloc.split('@')[-1] if not hostname: # HACK/FIXME: httpie-unixsocket's URLs have no hostname. hostname = 'localhost' # host:port => host_port hostname = hostname.replace(':', '_') path = ( config_dir / SESSIONS_DIR_NAME / hostname / f'{session_name}.json' ) session = Session(path) session.load() return session
true
2
166
httpie
httpie.sessions
Session
__init__
def __init__(self, path: Union[str, Path]): super().__init__(path=Path(path)) self['headers'] = {} self['cookies'] = {} self['auth'] = { 'type': None, 'username': None, 'password': None }
[ 57, 61 ]
false
[ "SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES" ]
import os import re from http.cookies import SimpleCookie from pathlib import Path from typing import Iterable, Optional, Union from urllib.parse import urlsplit from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, create_cookie from httpie.cli.dicts import RequestHeadersDict from httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR from httpie.plugins.registry import plugin_manager SESSIONS_DIR_NAME = 'sessions' DEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME VALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$') SESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-'] class Session(BaseConfigDict): helpurl = 'https://httpie.org/doc#sessions' about = 'HTTPie session file' def __init__(self, path: Union[str, Path]): super().__init__(path=Path(path)) self['headers'] = {} self['cookies'] = {} self['auth'] = { 'type': None, 'username': None, 'password': None }
false
0
167
httpie
httpie.sessions
Session
update_headers
def update_headers(self, request_headers: RequestHeadersDict): """ Update the session headers with the request ones while ignoring certain name prefixes. """ headers = self.headers for name, value in request_headers.items(): if value is None: continue # Ignore explicitly unset headers if type(value) is not str: value = value.decode('utf8') if name.lower() == 'user-agent' and value.startswith('HTTPie/'): continue if name.lower() == 'cookie': for cookie_name, morsel in SimpleCookie(value).items(): self['cookies'][cookie_name] = {'value': morsel.value} del request_headers[name] continue for prefix in SESSION_IGNORED_HEADER_PREFIXES: if name.lower().startswith(prefix.lower()): break else: headers[name] = value self['headers'] = dict(headers)
[ 67, 97 ]
false
[ "SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES" ]
import os import re from http.cookies import SimpleCookie from pathlib import Path from typing import Iterable, Optional, Union from urllib.parse import urlsplit from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, create_cookie from httpie.cli.dicts import RequestHeadersDict from httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR from httpie.plugins.registry import plugin_manager SESSIONS_DIR_NAME = 'sessions' DEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME VALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$') SESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-'] class Session(BaseConfigDict): helpurl = 'https://httpie.org/doc#sessions' about = 'HTTPie session file' def __init__(self, path: Union[str, Path]): super().__init__(path=Path(path)) self['headers'] = {} self['cookies'] = {} self['auth'] = { 'type': None, 'username': None, 'password': None } def update_headers(self, request_headers: RequestHeadersDict): """ Update the session headers with the request ones while ignoring certain name prefixes. """ headers = self.headers for name, value in request_headers.items(): if value is None: continue # Ignore explicitly unset headers if type(value) is not str: value = value.decode('utf8') if name.lower() == 'user-agent' and value.startswith('HTTPie/'): continue if name.lower() == 'cookie': for cookie_name, morsel in SimpleCookie(value).items(): self['cookies'][cookie_name] = {'value': morsel.value} del request_headers[name] continue for prefix in SESSION_IGNORED_HEADER_PREFIXES: if name.lower().startswith(prefix.lower()): break else: headers[name] = value self['headers'] = dict(headers)
true
2
168
httpie
httpie.sessions
Session
remove_cookies
def remove_cookies(self, names: Iterable[str]): for name in names: if name in self['cookies']: del self['cookies'][name]
[ 157, 160 ]
false
[ "SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES" ]
import os import re from http.cookies import SimpleCookie from pathlib import Path from typing import Iterable, Optional, Union from urllib.parse import urlsplit from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, create_cookie from httpie.cli.dicts import RequestHeadersDict from httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR from httpie.plugins.registry import plugin_manager SESSIONS_DIR_NAME = 'sessions' DEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME VALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$') SESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-'] class Session(BaseConfigDict): helpurl = 'https://httpie.org/doc#sessions' about = 'HTTPie session file' def __init__(self, path: Union[str, Path]): super().__init__(path=Path(path)) self['headers'] = {} self['cookies'] = {} self['auth'] = { 'type': None, 'username': None, 'password': None } def remove_cookies(self, names: Iterable[str]): for name in names: if name in self['cookies']: del self['cookies'][name]
true
2
169
httpie
httpie.uploads
prepare_request_body
def prepare_request_body( body: Union[str, bytes, IO, MultipartEncoder, RequestDataDict], body_read_callback: Callable[[bytes], bytes], content_length_header_value: int = None, chunked=False, offline=False, ) -> Union[str, bytes, IO, MultipartEncoder, ChunkedUploadStream]: is_file_like = hasattr(body, 'read') if isinstance(body, RequestDataDict): body = urlencode(body, doseq=True) if offline: if is_file_like: return body.read() return body if not is_file_like: if chunked: body = ChunkedUploadStream( # Pass the entire body as one chunk. stream=(chunk.encode() for chunk in [body]), callback=body_read_callback, ) else: # File-like object. if not super_len(body): # Zero-length -> assume stdin. if content_length_header_value is None and not chunked: # # Read the whole stdin to determine `Content-Length`. # # TODO: Instead of opt-in --chunked, consider making # `Transfer-Encoding: chunked` for STDIN opt-out via # something like --no-chunked. # This would be backwards-incompatible so wait until v3.0.0. # body = body.read() else: orig_read = body.read def new_read(*args): chunk = orig_read(*args) body_read_callback(chunk) return chunk body.read = new_read if chunked: if isinstance(body, MultipartEncoder): body = ChunkedMultipartUploadStream( encoder=body, ) else: body = ChunkedUploadStream( stream=body, callback=body_read_callback, ) return body
[ 36, 97 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict class ChunkedUploadStream: def __init__(self, stream: Iterable, callback: Callable): self.callback = callback self.stream = stream class ChunkedMultipartUploadStream: chunk_size = 100 * 1024 def __init__(self, encoder: MultipartEncoder): self.encoder = encoder def prepare_request_body( body: Union[str, bytes, IO, MultipartEncoder, RequestDataDict], body_read_callback: Callable[[bytes], bytes], content_length_header_value: int = None, chunked=False, offline=False, ) -> Union[str, bytes, IO, MultipartEncoder, ChunkedUploadStream]: is_file_like = hasattr(body, 'read') if isinstance(body, RequestDataDict): body = urlencode(body, doseq=True) if offline: if is_file_like: return body.read() return body if not is_file_like: if chunked: body = ChunkedUploadStream( # Pass the entire body as one chunk. stream=(chunk.encode() for chunk in [body]), callback=body_read_callback, ) else: # File-like object. if not super_len(body): # Zero-length -> assume stdin. if content_length_header_value is None and not chunked: # # Read the whole stdin to determine `Content-Length`. # # TODO: Instead of opt-in --chunked, consider making # `Transfer-Encoding: chunked` for STDIN opt-out via # something like --no-chunked. # This would be backwards-incompatible so wait until v3.0.0. # body = body.read() else: orig_read = body.read def new_read(*args): chunk = orig_read(*args) body_read_callback(chunk) return chunk body.read = new_read if chunked: if isinstance(body, MultipartEncoder): body = ChunkedMultipartUploadStream( encoder=body, ) else: body = ChunkedUploadStream( stream=body, callback=body_read_callback, ) return body
true
2
170
httpie
httpie.uploads
get_multipart_data_and_content_type
def get_multipart_data_and_content_type( data: MultipartRequestDataDict, boundary: str = None, content_type: str = None, ) -> Tuple[MultipartEncoder, str]: encoder = MultipartEncoder( fields=data.items(), boundary=boundary, ) if content_type: content_type = content_type.strip() if 'boundary=' not in content_type: content_type = f'{content_type}; boundary={encoder.boundary_value}' else: content_type = encoder.content_type data = encoder return data, content_type
[ 100, 117 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict def get_multipart_data_and_content_type( data: MultipartRequestDataDict, boundary: str = None, content_type: str = None, ) -> Tuple[MultipartEncoder, str]: encoder = MultipartEncoder( fields=data.items(), boundary=boundary, ) if content_type: content_type = content_type.strip() if 'boundary=' not in content_type: content_type = f'{content_type}; boundary={encoder.boundary_value}' else: content_type = encoder.content_type data = encoder return data, content_type
true
2
171
httpie
httpie.uploads
compress_request
def compress_request( request: requests.PreparedRequest, always: bool, ): deflater = zlib.compressobj() if isinstance(request.body, str): body_bytes = request.body.encode() elif hasattr(request.body, 'read'): body_bytes = request.body.read() else: body_bytes = request.body deflated_data = deflater.compress(body_bytes) deflated_data += deflater.flush() is_economical = len(deflated_data) < len(body_bytes) if is_economical or always: request.body = deflated_data request.headers['Content-Encoding'] = 'deflate' request.headers['Content-Length'] = str(len(deflated_data))
[ 120, 137 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict def compress_request( request: requests.PreparedRequest, always: bool, ): deflater = zlib.compressobj() if isinstance(request.body, str): body_bytes = request.body.encode() elif hasattr(request.body, 'read'): body_bytes = request.body.read() else: body_bytes = request.body deflated_data = deflater.compress(body_bytes) deflated_data += deflater.flush() is_economical = len(deflated_data) < len(body_bytes) if is_economical or always: request.body = deflated_data request.headers['Content-Encoding'] = 'deflate' request.headers['Content-Length'] = str(len(deflated_data))
true
2
172
httpie
httpie.uploads
ChunkedUploadStream
__iter__
def __iter__(self) -> Iterable[Union[str, bytes]]: for chunk in self.stream: self.callback(chunk) yield chunk
[ 16, 19 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict class ChunkedUploadStream: def __init__(self, stream: Iterable, callback: Callable): self.callback = callback self.stream = stream def __iter__(self) -> Iterable[Union[str, bytes]]: for chunk in self.stream: self.callback(chunk) yield chunk
true
2
173
httpie
httpie.uploads
ChunkedMultipartUploadStream
__iter__
def __iter__(self) -> Iterable[Union[str, bytes]]: while True: chunk = self.encoder.read(self.chunk_size) if not chunk: break yield chunk
[ 28, 33 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict class ChunkedMultipartUploadStream: chunk_size = 100 * 1024 def __init__(self, encoder: MultipartEncoder): self.encoder = encoder def __iter__(self) -> Iterable[Union[str, bytes]]: while True: chunk = self.encoder.read(self.chunk_size) if not chunk: break yield chunk
true
2
174
httpie
httpie.utils
load_json_preserve_order
def load_json_preserve_order(s): return json.loads(s, object_pairs_hook=OrderedDict)
[ 13, 14 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def load_json_preserve_order(s): return json.loads(s, object_pairs_hook=OrderedDict)
false
0
175
httpie
httpie.utils
repr_dict
def repr_dict(d: dict) -> str: return pformat(d)
[ 17, 18 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def repr_dict(d: dict) -> str: return pformat(d)
false
0
176
httpie
httpie.utils
humanize_bytes
def humanize_bytes(n, precision=2): # Author: Doug Latornell # Licence: MIT # URL: https://code.activestate.com/recipes/577081/ """Return a humanized string representation of a number of bytes. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 B' >>> humanize_bytes(1024, precision=1) '1.0 kB' >>> humanize_bytes(1024 * 123, precision=1) '123.0 kB' >>> humanize_bytes(1024 * 12342, precision=1) '12.1 MB' >>> humanize_bytes(1024 * 12342, precision=2) '12.05 MB' >>> humanize_bytes(1024 * 1234, precision=2) '1.21 MB' >>> humanize_bytes(1024 * 1234 * 1111, precision=2) '1.31 GB' >>> humanize_bytes(1024 * 1234 * 1111, precision=1) '1.3 GB' """ abbrevs = [ (1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20, 'MB'), (1 << 10, 'kB'), (1, 'B') ] if n == 1: return '1 B' for factor, suffix in abbrevs: if n >= factor: break # noinspection PyUnboundLocalVariable return '%.*f %s' % (precision, n / factor, suffix)
[ 21, 64 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def humanize_bytes(n, precision=2): # Author: Doug Latornell # Licence: MIT # URL: https://code.activestate.com/recipes/577081/ """Return a humanized string representation of a number of bytes. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 B' >>> humanize_bytes(1024, precision=1) '1.0 kB' >>> humanize_bytes(1024 * 123, precision=1) '123.0 kB' >>> humanize_bytes(1024 * 12342, precision=1) '12.1 MB' >>> humanize_bytes(1024 * 12342, precision=2) '12.05 MB' >>> humanize_bytes(1024 * 1234, precision=2) '1.21 MB' >>> humanize_bytes(1024 * 1234 * 1111, precision=2) '1.31 GB' >>> humanize_bytes(1024 * 1234 * 1111, precision=1) '1.3 GB' """ abbrevs = [ (1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20, 'MB'), (1 << 10, 'kB'), (1, 'B') ] if n == 1: return '1 B' for factor, suffix in abbrevs: if n >= factor: break # noinspection PyUnboundLocalVariable return '%.*f %s' % (precision, n / factor, suffix)
true
2
177
httpie
httpie.utils
get_content_type
def get_content_type(filename): """ Return the content type for ``filename`` in format appropriate for Content-Type headers, or ``None`` if the file type is unknown to ``mimetypes``. """ mime, encoding = mimetypes.guess_type(filename, strict=False) if mime: content_type = mime if encoding: content_type = '%s; charset=%s' % (mime, encoding) return content_type
[ 76, 88 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def get_content_type(filename): """ Return the content type for ``filename`` in format appropriate for Content-Type headers, or ``None`` if the file type is unknown to ``mimetypes``. """ mime, encoding = mimetypes.guess_type(filename, strict=False) if mime: content_type = mime if encoding: content_type = '%s; charset=%s' % (mime, encoding) return content_type
true
2
178
httpie
httpie.utils
get_expired_cookies
def get_expired_cookies( headers: List[Tuple[str, str]], now: float = None ) -> List[dict]: now = now or time.time() def is_expired(expires: Optional[float]) -> bool: return expires is not None and expires <= now attr_sets: List[Tuple[str, str]] = parse_ns_headers( value for name, value in headers if name.lower() == 'set-cookie' ) cookies = [ # The first attr name is the cookie name. dict(attrs[1:], name=attrs[0][0]) for attrs in attr_sets ] _max_age_to_expires(cookies=cookies, now=now) return [ { 'name': cookie['name'], 'path': cookie.get('path', '/') } for cookie in cookies if is_expired(expires=cookie.get('expires')) ]
[ 91, 113 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def get_expired_cookies( headers: List[Tuple[str, str]], now: float = None ) -> List[dict]: now = now or time.time() def is_expired(expires: Optional[float]) -> bool: return expires is not None and expires <= now attr_sets: List[Tuple[str, str]] = parse_ns_headers( value for name, value in headers if name.lower() == 'set-cookie' ) cookies = [ # The first attr name is the cookie name. dict(attrs[1:], name=attrs[0][0]) for attrs in attr_sets ] _max_age_to_expires(cookies=cookies, now=now) return [ { 'name': cookie['name'], 'path': cookie.get('path', '/') } for cookie in cookies if is_expired(expires=cookie.get('expires')) ]
false
0
179
httpie
httpie.utils
ExplicitNullAuth
__call__
def __call__(self, r): return r
[ 72, 73 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth class ExplicitNullAuth(requests.auth.AuthBase): def __call__(self, r): return r
false
0
180
isort
isort.exceptions
InvalidSettingsPath
__init__
def __init__(self, settings_path: str): super().__init__( f"isort was told to use the settings_path: {settings_path} as the base directory or " "file that represents the starting point of config file discovery, but it does not " "exist." ) self.settings_path = settings_path
[ 14, 20 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class InvalidSettingsPath(ISortError): def __init__(self, settings_path: str): super().__init__( f"isort was told to use the settings_path: {settings_path} as the base directory or " "file that represents the starting point of config file discovery, but it does not " "exist." ) self.settings_path = settings_path
false
0
181
isort
isort.exceptions
ExistingSyntaxErrors
__init__
def __init__(self, file_path: str): super().__init__( f"isort was told to sort imports within code that contains syntax errors: " f"{file_path}." ) self.file_path = file_path
[ 26, 31 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class ExistingSyntaxErrors(ISortError): def __init__(self, file_path: str): super().__init__( f"isort was told to sort imports within code that contains syntax errors: " f"{file_path}." ) self.file_path = file_path
false
0
182
isort
isort.exceptions
IntroducedSyntaxErrors
__init__
def __init__(self, file_path: str): super().__init__( f"isort introduced syntax errors when attempting to sort the imports contained within " f"{file_path}." ) self.file_path = file_path
[ 37, 42 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class IntroducedSyntaxErrors(ISortError): def __init__(self, file_path: str): super().__init__( f"isort introduced syntax errors when attempting to sort the imports contained within " f"{file_path}." ) self.file_path = file_path
false
0
183
isort
isort.exceptions
FileSkipped
__init__
def __init__(self, message: str, file_path: str): super().__init__(message) self.file_path = file_path
[ 48, 50 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class FileSkipped(ISortError): def __init__(self, message: str, file_path: str): super().__init__(message) self.file_path = file_path
false
0
184
isort
isort.exceptions
FileSkipComment
__init__
def __init__(self, file_path: str): super().__init__( f"{file_path} contains an file skip comment and was skipped.", file_path=file_path )
[ 56, 57 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class FileSkipComment(FileSkipped): def __init__(self, file_path: str): super().__init__( f"{file_path} contains an file skip comment and was skipped.", file_path=file_path )
false
0
185
isort
isort.exceptions
FileSkipSetting
__init__
def __init__(self, file_path: str): super().__init__( f"{file_path} was skipped as it's listed in 'skip' setting" " or matches a glob in 'skip_glob' setting", file_path=file_path, )
[ 65, 66 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class FileSkipSetting(FileSkipped): def __init__(self, file_path: str): super().__init__( f"{file_path} was skipped as it's listed in 'skip' setting" " or matches a glob in 'skip_glob' setting", file_path=file_path, )
false
0
186
isort
isort.exceptions
ProfileDoesNotExist
__init__
def __init__(self, profile: str): super().__init__( f"Specified profile of {profile} does not exist. " f"Available profiles: {','.join(profiles)}." ) self.profile = profile
[ 76, 81 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class ProfileDoesNotExist(ISortError): def __init__(self, profile: str): super().__init__( f"Specified profile of {profile} does not exist. " f"Available profiles: {','.join(profiles)}." ) self.profile = profile
false
0
187
isort
isort.exceptions
FormattingPluginDoesNotExist
__init__
def __init__(self, formatter: str): super().__init__(f"Specified formatting plugin of {formatter} does not exist. ") self.formatter = formatter
[ 87, 89 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class FormattingPluginDoesNotExist(ISortError): def __init__(self, formatter: str): super().__init__(f"Specified formatting plugin of {formatter} does not exist. ") self.formatter = formatter
false
0
188
isort
isort.exceptions
LiteralParsingFailure
__init__
def __init__(self, code: str, original_error: Exception): super().__init__( f"isort failed to parse the given literal {code}. It's important to note " "that isort literal sorting only supports simple literals parsable by " f"ast.literal_eval which gave the exception of {original_error}." ) self.code = code self.original_error = original_error
[ 97, 104 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class LiteralParsingFailure(ISortError): def __init__(self, code: str, original_error: Exception): super().__init__( f"isort failed to parse the given literal {code}. It's important to note " "that isort literal sorting only supports simple literals parsable by " f"ast.literal_eval which gave the exception of {original_error}." ) self.code = code self.original_error = original_error
false
0
189
isort
isort.exceptions
LiteralSortTypeMismatch
__init__
def __init__(self, kind: type, expected_kind: type): super().__init__( f"isort was told to sort a literal of type {expected_kind} but was given " f"a literal of type {kind}." ) self.kind = kind self.expected_kind = expected_kind
[ 112, 118 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class LiteralSortTypeMismatch(ISortError): def __init__(self, kind: type, expected_kind: type): super().__init__( f"isort was told to sort a literal of type {expected_kind} but was given " f"a literal of type {kind}." ) self.kind = kind self.expected_kind = expected_kind
false
0
190
isort
isort.exceptions
AssignmentsFormatMismatch
__init__
def __init__(self, code: str): super().__init__( "isort was told to sort a section of assignments, however the given code:\n\n" f"{code}\n\n" "Does not match isort's strict single line formatting requirement for assignment " "sorting:\n\n" "{variable_name} = {value}\n" "{variable_name2} = {value2}\n" "...\n\n" ) self.code = code
[ 126, 136 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class AssignmentsFormatMismatch(ISortError): def __init__(self, code: str): super().__init__( "isort was told to sort a section of assignments, however the given code:\n\n" f"{code}\n\n" "Does not match isort's strict single line formatting requirement for assignment " "sorting:\n\n" "{variable_name} = {value}\n" "{variable_name2} = {value2}\n" "...\n\n" ) self.code = code
false
0
191
isort
isort.exceptions
UnsupportedSettings
__init__
def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]): errors = "\n".join( self._format_option(name, **option) for name, option in unsupported_settings.items() ) super().__init__( "isort was provided settings that it doesn't support:\n\n" f"{errors}\n\n" "For a complete and up-to-date listing of supported settings see: " "https://pycqa.github.io/isort/docs/configuration/options/.\n" ) self.unsupported_settings = unsupported_settings
[ 148, 159 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class UnsupportedSettings(ISortError): def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]): errors = "\n".join( self._format_option(name, **option) for name, option in unsupported_settings.items() ) super().__init__( "isort was provided settings that it doesn't support:\n\n" f"{errors}\n\n" "For a complete and up-to-date listing of supported settings see: " "https://pycqa.github.io/isort/docs/configuration/options/.\n" ) self.unsupported_settings = unsupported_settings
false
0
192
isort
isort.exceptions
UnsupportedEncoding
__init__
def __init__(self, filename: Union[str, Path]): super().__init__(f"Unknown or unsupported encoding in {filename}") self.filename = filename
[ 165, 167 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class UnsupportedEncoding(ISortError): def __init__(self, filename: Union[str, Path]): super().__init__(f"Unknown or unsupported encoding in {filename}") self.filename = filename
false
0
193
isort
isort.exceptions
MissingSection
__init__
def __init__(self, import_module: str, section: str): super().__init__( f"Found {import_module} import while parsing, but {section} was not included " "in the `sections` setting of your config. Please add it before continuing\n" "See https://pycqa.github.io/isort/#custom-sections-and-ordering " "for more info." )
[ 173, 174 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class MissingSection(ISortError): def __init__(self, import_module: str, section: str): super().__init__( f"Found {import_module} import while parsing, but {section} was not included " "in the `sections` setting of your config. Please add it before continuing\n" "See https://pycqa.github.io/isort/#custom-sections-and-ordering " "for more info." )
false
0
194
isort
isort.format
format_simplified
def format_simplified(import_line: str) -> str: import_line = import_line.strip() if import_line.startswith("from "): import_line = import_line.replace("from ", "") import_line = import_line.replace(" import ", ".") elif import_line.startswith("import "): import_line = import_line.replace("import ", "") return import_line
[ 20, 28 ]
false
[ "ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN" ]
import re import sys from datetime import datetime from difflib import unified_diff from pathlib import Path from typing import Optional, TextIO ADDED_LINE_PATTERN = re.compile(r"\+[^+]") REMOVED_LINE_PATTERN = re.compile(r"-[^-]") def format_simplified(import_line: str) -> str: import_line = import_line.strip() if import_line.startswith("from "): import_line = import_line.replace("from ", "") import_line = import_line.replace(" import ", ".") elif import_line.startswith("import "): import_line = import_line.replace("import ", "") return import_line
true
2
195
isort
isort.format
format_natural
def format_natural(import_line: str) -> str: import_line = import_line.strip() if not import_line.startswith("from ") and not import_line.startswith("import "): if "." not in import_line: return f"import {import_line}" parts = import_line.split(".") end = parts.pop(-1) return f"from {'.'.join(parts)} import {end}" return import_line
[ 31, 40 ]
false
[ "ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN" ]
import re import sys from datetime import datetime from difflib import unified_diff from pathlib import Path from typing import Optional, TextIO ADDED_LINE_PATTERN = re.compile(r"\+[^+]") REMOVED_LINE_PATTERN = re.compile(r"-[^-]") def format_natural(import_line: str) -> str: import_line = import_line.strip() if not import_line.startswith("from ") and not import_line.startswith("import "): if "." not in import_line: return f"import {import_line}" parts = import_line.split(".") end = parts.pop(-1) return f"from {'.'.join(parts)} import {end}" return import_line
true
2
196
isort
isort.format
ask_whether_to_apply_changes_to_file
def ask_whether_to_apply_changes_to_file(file_path: str) -> bool: answer = None while answer not in ("yes", "y", "no", "n", "quit", "q"): answer = input(f"Apply suggested changes to '{file_path}' [y/n/q]? ") # nosec answer = answer.lower() if answer in ("no", "n"): return False if answer in ("quit", "q"): sys.exit(1) return True
[ 76, 85 ]
false
[ "ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN" ]
import re import sys from datetime import datetime from difflib import unified_diff from pathlib import Path from typing import Optional, TextIO ADDED_LINE_PATTERN = re.compile(r"\+[^+]") REMOVED_LINE_PATTERN = re.compile(r"-[^-]") def ask_whether_to_apply_changes_to_file(file_path: str) -> bool: answer = None while answer not in ("yes", "y", "no", "n", "quit", "q"): answer = input(f"Apply suggested changes to '{file_path}' [y/n/q]? ") # nosec answer = answer.lower() if answer in ("no", "n"): return False if answer in ("quit", "q"): sys.exit(1) return True
true
2
197
isort
isort.format
create_terminal_printer
def create_terminal_printer(color: bool, output: Optional[TextIO] = None): if color and colorama_unavailable: no_colorama_message = ( "\n" "Sorry, but to use --color (color_output) the colorama python package is required.\n\n" "Reference: https://pypi.org/project/colorama/\n\n" "You can either install it separately on your system or as the colors extra " "for isort. Ex: \n\n" "$ pip install isort[colors]\n" ) print(no_colorama_message, file=sys.stderr) sys.exit(1) return ColoramaPrinter(output) if color else BasicPrinter(output)
[ 136, 149 ]
false
[ "ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN" ]
import re import sys from datetime import datetime from difflib import unified_diff from pathlib import Path from typing import Optional, TextIO ADDED_LINE_PATTERN = re.compile(r"\+[^+]") REMOVED_LINE_PATTERN = re.compile(r"-[^-]") class BasicPrinter: ERROR = "ERROR" SUCCESS = "SUCCESS" def __init__(self, output: Optional[TextIO] = None): self.output = output or sys.stdout class ColoramaPrinter(BasicPrinter): def __init__(self, output: Optional[TextIO] = None): super().__init__(output=output) # Note: this constants are instance variables instead ofs class variables # because they refer to colorama which might not be installed. self.ERROR = self.style_text("ERROR", colorama.Fore.RED) self.SUCCESS = self.style_text("SUCCESS", colorama.Fore.GREEN) self.ADDED_LINE = colorama.Fore.GREEN self.REMOVED_LINE = colorama.Fore.RED def create_terminal_printer(color: bool, output: Optional[TextIO] = None): if color and colorama_unavailable: no_colorama_message = ( "\n" "Sorry, but to use --color (color_output) the colorama python package is required.\n\n" "Reference: https://pypi.org/project/colorama/\n\n" "You can either install it separately on your system or as the colors extra " "for isort. Ex: \n\n" "$ pip install isort[colors]\n" ) print(no_colorama_message, file=sys.stderr) sys.exit(1) return ColoramaPrinter(output) if color else BasicPrinter(output)
true
2
243
py_backwards
py_backwards.compiler
compile_files
def compile_files(input_: str, output: str, target: CompilationTarget, root: Optional[str] = None) -> CompilationResult: """Compiles all files from input_ to output.""" dependencies = set() start = time() count = 0 for paths in get_input_output_paths(input_, output, root): count += 1 dependencies.update(_compile_file(paths, target)) return CompilationResult(count, time() - start, target, sorted(dependencies))
[ 76, 85 ]
false
[]
from copy import deepcopy from time import time from traceback import format_exc from typing import List, Tuple, Optional from typed_ast import ast3 as ast from astunparse import unparse, dump from autopep8 import fix_code from .files import get_input_output_paths, InputOutput from .transformers import transformers from .types import CompilationTarget, CompilationResult from .exceptions import CompilationError, TransformationError from .utils.helpers import debug def compile_files(input_: str, output: str, target: CompilationTarget, root: Optional[str] = None) -> CompilationResult: """Compiles all files from input_ to output.""" dependencies = set() start = time() count = 0 for paths in get_input_output_paths(input_, output, root): count += 1 dependencies.update(_compile_file(paths, target)) return CompilationResult(count, time() - start, target, sorted(dependencies))
true
2
244
py_backwards
py_backwards.conf
init_settings
def init_settings(args: Namespace) -> None: if args.debug: settings.debug = True
[ 11, 13 ]
false
[ "settings" ]
from argparse import Namespace settings = Settings() def init_settings(args: Namespace) -> None: if args.debug: settings.debug = True
true
2