desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Add a file to the current component of the directory, starting a new one
if there is no current component. By default, the file name in the source
and the file table will be identical. If the src file is specified, it is
interpreted relative to the current directory. Optionally, a version and a
language can be specifi... | def add_file(self, file, src=None, version=None, language=None):
| if (not self.component):
self.start_component(self.logical, current_feature, 0)
if (not src):
src = file
file = os.path.basename(file)
absolute = os.path.join(self.absolute, src)
assert (not re.search('[\\?|><:/*]"', file))
if (file in self.keyfiles):
logical = self.k... |
'Add a list of files to the current component as specified in the
glob pattern. Individual files can be excluded in the exclude list.'
| def glob(self, pattern, exclude=None):
| files = glob.glob1(self.absolute, pattern)
for f in files:
if (exclude and (f in exclude)):
continue
self.add_file(f)
return files
|
'Remove .pyc/.pyo files on uninstall'
| def remove_pyc(self):
| add_data(self.db, 'RemoveFile', [((self.component + 'c'), self.component, '*.pyc', self.logical, 2), ((self.component + 'o'), self.component, '*.pyo', self.logical, 2)])
|
'Return current line number and offset.'
| def getpos(self):
| return (self.lineno, self.offset)
|
'Visit a node.'
| def visit(self, node):
| method = ('visit_' + node.__class__.__name__)
visitor = getattr(self, method, self.generic_visit)
return visitor(node)
|
'Called if no explicit visitor function exists for a node.'
| def generic_visit(self, node):
| for (field, value) in iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(value)
|
'Initializer.
Takes an optional alternative filename for the pattern grammar.'
| def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE):
| self.grammar = driver.load_grammar(grammar_file)
self.syms = pygram.Symbols(self.grammar)
self.pygrammar = pygram.python_grammar
self.pysyms = pygram.python_symbols
self.driver = driver.Driver(self.grammar, convert=pattern_convert)
|
'Compiles a pattern string to a nested pytree.*Pattern object.'
| def compile_pattern(self, input, debug=False, with_tree=False):
| tokens = tokenize_wrapper(input)
try:
root = self.driver.parse_tokens(tokens, debug=debug)
except parse.ParseError as e:
raise PatternSyntaxError(str(e))
if with_tree:
return (self.compile_node(root), root)
else:
return self.compile_node(root)
|
'Compiles a node, recursively.
This is one big switch on the node type.'
| def compile_node(self, node):
| if (node.type == self.syms.Matcher):
node = node.children[0]
if (node.type == self.syms.Alternatives):
alts = [self.compile_node(ch) for ch in node.children[::2]]
if (len(alts) == 1):
return alts[0]
p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1)
... |
'Constructor.
The grammar argument is a grammar.Grammar instance; see the
grammar module for more information.
The parser is not ready yet for parsing; you must call the
setup() method to get it started.
The optional convert argument is a function mapping concrete
syntax tree nodes to abstract syntax tree nodes. If no... | def __init__(self, grammar, convert=None):
| self.grammar = grammar
self.convert = (convert or (lambda grammar, node: node))
|
'Prepare for parsing.
This *must* be called before starting to parse.
The optional argument is an alternative start symbol; it
defaults to the grammar\'s start symbol.
You can use a Parser instance to parse any number of programs;
each time you call setup() the parser is reset to an initial
state determined by the (imp... | def setup(self, start=None):
| if (start is None):
start = self.grammar.start
newnode = (start, None, None, [])
stackentry = (self.grammar.dfas[start], 0, newnode)
self.stack = [stackentry]
self.rootnode = None
self.used_names = set()
|
'Add a token; return True iff this is the end of the program.'
| def addtoken(self, type, value, context):
| ilabel = self.classify(type, value, context)
while True:
(dfa, state, node) = self.stack[(-1)]
(states, first) = dfa
arcs = states[state]
for (i, newstate) in arcs:
(t, v) = self.grammar.labels[i]
if (ilabel == i):
assert (t < 256)
... |
'Turn a token into a label. (Internal)'
| def classify(self, type, value, context):
| if (type == token.NAME):
self.used_names.add(value)
ilabel = self.grammar.keywords.get(value)
if (ilabel is not None):
return ilabel
ilabel = self.grammar.tokens.get(type)
if (ilabel is None):
raise ParseError('bad token', type, value, context)
return ilabe... |
'Shift a token. (Internal)'
| def shift(self, type, value, newstate, context):
| (dfa, state, node) = self.stack[(-1)]
newnode = (type, value, context, None)
newnode = self.convert(self.grammar, newnode)
if (newnode is not None):
node[(-1)].append(newnode)
self.stack[(-1)] = (dfa, newstate, node)
|
'Push a nonterminal. (Internal)'
| def push(self, type, newdfa, newstate, context):
| (dfa, state, node) = self.stack[(-1)]
newnode = (type, None, context, [])
self.stack[(-1)] = (dfa, newstate, node)
self.stack.append((newdfa, 0, newnode))
|
'Pop a nonterminal. (Internal)'
| def pop(self):
| (popdfa, popstate, popnode) = self.stack.pop()
newnode = self.convert(self.grammar, popnode)
if (newnode is not None):
if self.stack:
(dfa, state, node) = self.stack[(-1)]
node[(-1)].append(newnode)
else:
self.rootnode = newnode
self.rootnode.u... |
'Dump the grammar tables to a pickle file.'
| def dump(self, filename):
| with open(filename, 'wb') as f:
pickle.dump(self.__dict__, f, 2)
|
'Load the grammar tables from a pickle file.'
| def load(self, filename):
| with open(filename, 'rb') as f:
d = pickle.load(f)
self.__dict__.update(d)
|
'Copy the grammar.'
| def copy(self):
| new = self.__class__()
for dict_attr in ('symbol2number', 'number2symbol', 'dfas', 'keywords', 'tokens', 'symbol2label'):
setattr(new, dict_attr, getattr(self, dict_attr).copy())
new.labels = self.labels[:]
new.states = self.states[:]
new.start = self.start
return new
|
'Dump the grammar tables to standard output, for debugging.'
| def report(self):
| from pprint import pprint
print 's2n'
pprint(self.symbol2number)
print 'n2s'
pprint(self.number2symbol)
print 'states'
pprint(self.states)
print 'dfas'
pprint(self.dfas)
print 'labels'
pprint(self.labels)
print ('start', self.start)
|
'Parse a series of tokens and return the syntax tree.'
| def parse_tokens(self, tokens, debug=False):
| p = parse.Parser(self.grammar, self.convert)
p.setup()
lineno = 1
column = 0
type = value = start = end = line_text = None
prefix = ''
for quintuple in tokens:
(type, value, start, end, line_text) = quintuple
if (start != (lineno, column)):
assert ((lineno, column... |
'Parse a stream and return the syntax tree.'
| def parse_stream_raw(self, stream, debug=False):
| tokens = tokenize.generate_tokens(stream.readline)
return self.parse_tokens(tokens, debug)
|
'Parse a stream and return the syntax tree.'
| def parse_stream(self, stream, debug=False):
| return self.parse_stream_raw(stream, debug)
|
'Parse a file and return the syntax tree.'
| def parse_file(self, filename, encoding=None, debug=False):
| stream = codecs.open(filename, 'r', encoding)
try:
return self.parse_stream(stream, debug)
finally:
stream.close()
|
'Parse a string and return the syntax tree.'
| def parse_string(self, text, debug=False):
| tokens = tokenize.generate_tokens(io.StringIO(text).readline)
return self.parse_tokens(tokens, debug)
|
'Load the grammar tables from the text files written by pgen.'
| def run(self, graminit_h, graminit_c):
| self.parse_graminit_h(graminit_h)
self.parse_graminit_c(graminit_c)
self.finish_off()
|
'Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back.'
| def parse_graminit_h(self, filename):
| try:
f = open(filename)
except OSError as err:
print ("Can't open %s: %s" % (filename, err))
return False
self.symbol2number = {}
self.number2symbol = {}
lineno = 0
for line in f:
lineno += 1
mo = re.match('^#define\\s+(\\w+)\\s+(\\d+)$', line)
... |
'Parse the .c file written by pgen. (Internal)
The file looks as follows. The first two lines are always this:
#include "pgenheaders.h"
#include "grammar.h"
After that come four blocks:
1) one or more state definitions
2) a table defining dfas
3) a table defining labels
4) a struct defining the grammar
A state defini... | def parse_graminit_c(self, filename):
| try:
f = open(filename)
except OSError as err:
print ("Can't open %s: %s" % (filename, err))
return False
lineno = 0
(lineno, line) = ((lineno + 1), next(f))
assert (line == '#include "pgenheaders.h"\n'), (lineno, line)
(lineno, line) = ((lineno + 1), next(f))... |
'Create additional useful structures. (Internal).'
| def finish_off(self):
| self.keywords = {}
self.tokens = {}
for (ilabel, (type, value)) in enumerate(self.labels):
if ((type == token.NAME) and (value is not None)):
self.keywords[value] = ilabel
elif (value is None):
self.tokens[type] = ilabel
|
'Help the next test'
| def _Call(self, name, args=None, prefix=None):
| children = []
if isinstance(args, list):
for arg in args:
children.append(arg)
children.append(Comma())
children.pop()
return Call(Name(name), children, prefix)
|
'Setup a test source tree and output destination tree.'
| def setup_test_source_trees(self):
| self.temp_dir = tempfile.mkdtemp()
self.py2_src_dir = os.path.join(self.temp_dir, 'python2_project')
self.py3_dest_dir = os.path.join(self.temp_dir, 'python3_project')
os.mkdir(self.py2_src_dir)
os.mkdir(self.py3_dest_dir)
self.setup_files = []
open(os.path.join(self.py2_src_dir, '__init__.p... |
'2to3 a single directory with a new output dir and suffix.'
| def test_filename_changing_on_output_single_dir(self):
| self.setup_test_source_trees()
out = io.StringIO()
err = io.StringIO()
suffix = 'TEST'
ret = self.run_2to3_capture(['-n', '--add-suffix', suffix, '--write-unchanged-files', '--no-diffs', '--output-dir', self.py3_dest_dir, self.py2_src_dir], io.StringIO(''), out, err)
self.assertEqual(ret, 0)
... |
'2to3 two files in one directory with a new output dir.'
| def test_filename_changing_on_output_two_files(self):
| self.setup_test_source_trees()
err = io.StringIO()
py2_files = [self.trivial_py2_file, self.init_py2_file]
expected_files = set((os.path.basename(name) for name in py2_files))
ret = self.run_2to3_capture((['-n', '-w', '--write-unchanged-files', '--no-diffs', '--output-dir', self.py3_dest_dir] + py2_... |
'2to3 a single file with a new output dir.'
| def test_filename_changing_on_output_single_file(self):
| self.setup_test_source_trees()
err = io.StringIO()
ret = self.run_2to3_capture(['-n', '-w', '--no-diffs', '--output-dir', self.py3_dest_dir, self.trivial_py2_file], io.StringIO(''), io.StringIO(), err)
self.assertEqual(ret, 0)
stderr = err.getvalue()
self.assertIn(('Output in %r will ... |
'Reduces a fixer\'s pattern tree to a linear path and adds it
to the matcher(a common Aho-Corasick automaton). The fixer is
appended on the matching states and called when they are
reached'
| def add_fixer(self, fixer):
| self.fixers.append(fixer)
tree = reduce_tree(fixer.pattern_tree)
linear = tree.get_linear_subpattern()
match_nodes = self.add(linear, start=self.root)
for match_node in match_nodes:
match_node.fixers.append(fixer)
|
'Recursively adds a linear pattern to the AC automaton'
| def add(self, pattern, start):
| if (not pattern):
return [start]
if isinstance(pattern[0], tuple):
match_nodes = []
for alternative in pattern[0]:
end_nodes = self.add(alternative, start=start)
for end in end_nodes:
match_nodes.extend(self.add(pattern[1:], end))
return ma... |
'The main interface with the bottom matcher. The tree is
traversed from the bottom using the constructed
automaton. Nodes are only checked once as the tree is
retraversed. When the automaton fails, we give it one more
shot(in case the above tree matches as a whole with the
rejected leaf), then we break for the next lea... | def run(self, leaves):
| current_ac_node = self.root
results = defaultdict(list)
for leaf in leaves:
current_ast_node = leaf
while current_ast_node:
current_ast_node.was_checked = True
for child in current_ast_node.children:
if (isinstance(child, pytree.Leaf) and (child.value ... |
'Prints a graphviz diagram of the BM automaton(for debugging)'
| def print_ac(self):
| print 'digraph g{'
def print_node(node):
for subnode_key in node.transition_table.keys():
subnode = node.transition_table[subnode_key]
print ('%d -> %d [label=%s] //%s' % (node.id, subnode.id, type_repr(subnode_key), str(subnode.fixers)))
if (subnode_ke... |
'Initializer.
Creates an attribute for each grammar symbol (nonterminal),
whose value is the symbol\'s type (an int >= 256).'
| def __init__(self, grammar):
| for (name, symbol) in grammar.symbol2number.items():
setattr(self, name, symbol)
|
'Transform for the basic import case. Replaces the old
import name with a comma separated list of its
replacements.'
| def transform_import(self, node, results):
| import_mod = results.get('module')
pref = import_mod.prefix
names = []
for name in MAPPING[import_mod.value][:(-1)]:
names.extend([Name(name[0], prefix=pref), Comma()])
names.append(Name(MAPPING[import_mod.value][(-1)][0], prefix=pref))
import_mod.replace(names)
|
'Transform for imports of specific module elements. Replaces
the module to be imported from with the appropriate new
module.'
| def transform_member(self, node, results):
| mod_member = results.get('mod_member')
pref = mod_member.prefix
member = results.get('member')
if member:
if isinstance(member, list):
member = member[0]
new_name = None
for change in MAPPING[mod_member.value]:
if (member.value in change[1]):
... |
'Transform for calls to module members in code.'
| def transform_dot(self, node, results):
| module_dot = results.get('bare_with_attr')
member = results.get('member')
new_name = None
if isinstance(member, list):
member = member[0]
for change in MAPPING[module_dot.value]:
if (member.value in change[1]):
new_name = change[0]
break
if new_name:
... |
'Initializer.
Args:
fixer_names: a list of fixers to import
options: an dict with configuration.
explicit: a list of fixers to run even if they are explicit.'
| def __init__(self, fixer_names, options=None, explicit=None):
| self.fixers = fixer_names
self.explicit = (explicit or [])
self.options = self._default_options.copy()
if (options is not None):
self.options.update(options)
if self.options['print_function']:
self.grammar = pygram.python_grammar_no_print_statement
else:
self.grammar = py... |
'Inspects the options to load the requested patterns and handlers.
Returns:
(pre_order, post_order), where pre_order is the list of fixers that
want a pre-order AST traversal, and post_order is the list that want
post-order traversal.'
| def get_fixers(self):
| pre_order_fixers = []
post_order_fixers = []
for fix_mod_path in self.fixers:
mod = __import__(fix_mod_path, {}, {}, ['*'])
fix_name = fix_mod_path.rsplit('.', 1)[(-1)]
if fix_name.startswith(self.FILE_PREFIX):
fix_name = fix_name[len(self.FILE_PREFIX):]
parts = f... |
'Called when an error occurs.'
| def log_error(self, msg, *args, **kwds):
| raise
|
'Hook to log a message.'
| def log_message(self, msg, *args):
| if args:
msg = (msg % args)
self.logger.info(msg)
|
'Called with the old version, new version, and filename of a
refactored file.'
| def print_output(self, old_text, new_text, filename, equal):
| pass
|
'Refactor a list of files and directories.'
| def refactor(self, items, write=False, doctests_only=False):
| for dir_or_file in items:
if os.path.isdir(dir_or_file):
self.refactor_dir(dir_or_file, write, doctests_only)
else:
self.refactor_file(dir_or_file, write, doctests_only)
|
'Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with \'.\' are skipped.'
| def refactor_dir(self, dir_name, write=False, doctests_only=False):
| py_ext = (os.extsep + 'py')
for (dirpath, dirnames, filenames) in os.walk(dir_name):
self.log_debug('Descending into %s', dirpath)
dirnames.sort()
filenames.sort()
for name in filenames:
if ((not name.startswith('.')) and (os.path.splitext(name)[1] == py_ext)):
... |
'Do our best to decode a Python source file correctly.'
| def _read_python_source(self, filename):
| try:
f = open(filename, 'rb')
except OSError as err:
self.log_error("Can't open %s: %s", filename, err)
return (None, None)
try:
encoding = tokenize.detect_encoding(f.readline)[0]
finally:
f.close()
with _open_with_encoding(filename, 'r', encoding=enc... |
'Refactors a file.'
| def refactor_file(self, filename, write=False, doctests_only=False):
| (input, encoding) = self._read_python_source(filename)
if (input is None):
return
input += '\n'
if doctests_only:
self.log_debug('Refactoring doctests in %s', filename)
output = self.refactor_docstring(input, filename)
if (self.write_unchanged_files or (output !=... |
'Refactor a given input string.
Args:
data: a string holding the code to be refactored.
name: a human-readable name for use in error/log messages.
Returns:
An AST corresponding to the refactored input stream; None if
there were errors during the parse.'
| def refactor_string(self, data, name):
| features = _detect_future_features(data)
if ('print_function' in features):
self.driver.grammar = pygram.python_grammar_no_print_statement
try:
tree = self.driver.parse_string(data)
except Exception as err:
self.log_error("Can't parse %s: %s: %s", name, err.__class__.... |
'Refactors a parse tree (modifying the tree in place).
For compatible patterns the bottom matcher module is
used. Otherwise the tree is traversed node-to-node for
matches.
Args:
tree: a pytree.Node instance representing the root of the tree
to be refactored.
name: a human-readable name for this tree.
Returns:
True if t... | def refactor_tree(self, tree, name):
| for fixer in chain(self.pre_order, self.post_order):
fixer.start_tree(tree, name)
self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
self.traverse_by(self.bmi_post_order_heads, tree.post_order())
match_set = self.BM.run(tree.leaves())
while any(match_set.values()):
for fixe... |
'Traverse an AST, applying a set of fixers to each node.
This is a helper method for refactor_tree().
Args:
fixers: a list of fixer instances.
traversal: a generator that yields AST nodes.
Returns:
None'
| def traverse_by(self, fixers, traversal):
| if (not fixers):
return
for node in traversal:
for fixer in fixers[node.type]:
results = fixer.match(node)
if results:
new = fixer.transform(node, results)
if (new is not None):
node.replace(new)
node... |
'Called when a file has been refactored and there may be changes.'
| def processed_file(self, new_text, filename, old_text=None, write=False, encoding=None):
| self.files.append(filename)
if (old_text is None):
old_text = self._read_python_source(filename)[0]
if (old_text is None):
return
equal = (old_text == new_text)
self.print_output(old_text, new_text, filename, equal)
if equal:
self.log_debug('No changes to ... |
'Writes a string to a file.
It first shows a unified diff between the old text and the new text, and
then rewrites the file; the latter is only done if the write option is
set.'
| def write_file(self, new_text, filename, old_text, encoding=None):
| try:
f = _open_with_encoding(filename, 'w', encoding=encoding)
except OSError as err:
self.log_error("Can't create %s: %s", filename, err)
return
try:
f.write(_to_system_newlines(new_text))
except OSError as err:
self.log_error("Can't write %s: %... |
'Refactors a docstring, looking for doctests.
This returns a modified version of the input string. It looks
for doctests, which start with a ">>>" prompt, and may be
continued with "..." prompts, as long as the "..." is indented
the same as the ">>>".
(Unfortunately we can\'t use the doctest module\'s parser,
since, l... | def refactor_docstring(self, input, filename):
| result = []
block = None
block_lineno = None
indent = None
lineno = 0
for line in input.splitlines(keepends=True):
lineno += 1
if line.lstrip().startswith(self.PS1):
if (block is not None):
result.extend(self.refactor_doctest(block, block_lineno, inden... |
'Refactors one doctest.
A doctest is given as a block of lines, the first of which starts
with ">>>" (possibly indented), while the remaining lines start
with "..." (identically indented).'
| def refactor_doctest(self, block, lineno, indent, filename):
| try:
tree = self.parse_block(block, lineno, indent)
except Exception as err:
if self.logger.isEnabledFor(logging.DEBUG):
for line in block:
self.log_debug('Source: %s', line.rstrip('\n'))
self.log_error("Can't parse docstring in %s line %s... |
'Parses a block into a tree.
This is necessary to get correct line number / offset information
in the parser diagnostics and embedded into the parse tree.'
| def parse_block(self, block, lineno, indent):
| tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
tree.future_features = frozenset()
return tree
|
'Wraps a tokenize stream to systematically modify start/end.'
| def wrap_toks(self, block, lineno, indent):
| tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__)
for (type, value, (line0, col0), (line1, col1), line_text) in tokens:
line0 += (lineno - 1)
line1 += (lineno - 1)
(yield (type, value, (line0, col0), (line1, col1), line_text))
|
'Generates lines as expected by tokenize from a list of lines.
This strips the first len(indent + self.PS1) characters off each line.'
| def gen_lines(self, block, indent):
| prefix1 = (indent + self.PS1)
prefix2 = (indent + self.PS2)
prefix = prefix1
for line in block:
if line.startswith(prefix):
(yield line[len(prefix):])
elif (line == (prefix.rstrip() + '\n')):
(yield '\n')
else:
raise AssertionError(('line=%r, ... |
'Initializer. Subclass may override.
Args:
options: an dict containing the options passed to RefactoringTool
that could be used to customize the fixer through the command line.
log: a list to append warnings and other messages to.'
| def __init__(self, options, log):
| self.options = options
self.log = log
self.compile_pattern()
|
'Compiles self.PATTERN into self.pattern.
Subclass may override if it doesn\'t want to use
self.{pattern,PATTERN} in .match().'
| def compile_pattern(self):
| if (self.PATTERN is not None):
PC = PatternCompiler()
(self.pattern, self.pattern_tree) = PC.compile_pattern(self.PATTERN, with_tree=True)
|
'Set the filename.
The main refactoring tool should call this.'
| def set_filename(self, filename):
| self.filename = filename
|
'Returns match for a given parse tree node.
Should return a true or false object (not necessarily a bool).
It may return a non-empty dict of matching sub-nodes as
returned by a matching pattern.
Subclass may override.'
| def match(self, node):
| results = {'node': node}
return (self.pattern.match(node, results) and results)
|
'Returns the transformation for a given parse tree node.
Args:
node: the root of the parse tree that matched the fixer.
results: a dict mapping symbolic names to part of the match.
Returns:
None, or a node that is a modified copy of the
argument node. The node argument may also be modified in-place to
effect the same ... | def transform(self, node, results):
| raise NotImplementedError()
|
'Return a string suitable for use as an identifier
The new name is guaranteed not to conflict with other identifiers.'
| def new_name(self, template='xxx_todo_changeme'):
| name = template
while (name in self.used_names):
name = (template + str(next(self.numbers)))
self.used_names.add(name)
return name
|
'Warn the user that a given chunk of code is not valid Python 3,
but that it cannot be converted automatically.
First argument is the top-level node for the code in question.
Optional second argument is why it can\'t be converted.'
| def cannot_convert(self, node, reason=None):
| lineno = node.get_lineno()
for_output = node.clone()
for_output.prefix = ''
msg = 'Line %d: could not convert: %s'
self.log_message((msg % (lineno, for_output)))
if reason:
self.log_message(reason)
|
'Used for warning the user about possible uncertainty in the
translation.
First argument is the top-level node for the code in question.
Optional second argument is why it can\'t be converted.'
| def warning(self, node, reason):
| lineno = node.get_lineno()
self.log_message(('Line %d: %s' % (lineno, reason)))
|
'Some fixers need to maintain tree-wide state.
This method is called once, at the start of tree fix-up.
tree - the root node of the tree to be processed.
filename - the name of the file the tree came from.'
| def start_tree(self, tree, filename):
| self.used_names = tree.used_names
self.set_filename(filename)
self.numbers = itertools.count(1)
self.first_log = True
|
'Some fixers need to maintain tree-wide state.
This method is called once, at the conclusion of tree fix-up.
tree - the root node of the tree to be processed.
filename - the name of the file the tree came from.'
| def finish_tree(self, tree, filename):
| pass
|
'Convert/check value type.'
| def _convert_string_type(self, value):
| if (type(value) is str):
return value
raise AssertionError('Header names/values must be of type str (got {0})'.format(repr(value)))
|
'Return the total number of headers, including duplicates.'
| def __len__(self):
| return len(self._headers)
|
'Set the value of a header.'
| def __setitem__(self, name, val):
| del self[name]
self._headers.append((self._convert_string_type(name), self._convert_string_type(val)))
|
'Delete all occurrences of a header, if present.
Does *not* raise an exception if the header is missing.'
| def __delitem__(self, name):
| name = self._convert_string_type(name.lower())
self._headers[:] = [kv for kv in self._headers if (kv[0].lower() != name)]
|
'Get the first header value for \'name\'
Return None if the header is missing instead of raising an exception.
Note that if the header appeared multiple times, the first exactly which
occurrance gets returned is undefined. Use getall() to get all
the values matching a header field name.'
| def __getitem__(self, name):
| return self.get(name)
|
'Return true if the message contains the header.'
| def __contains__(self, name):
| return (self.get(name) is not None)
|
'Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original header
list or were added to this instance, and may contain duplicates. Any
fields deleted and re-inserted are always appended to the header list.
If no fields exist with the given name, returns an emp... | def get_all(self, name):
| name = self._convert_string_type(name.lower())
return [kv[1] for kv in self._headers if (kv[0].lower() == name)]
|
'Get the first header value for \'name\', or return \'default\''
| def get(self, name, default=None):
| name = self._convert_string_type(name.lower())
for (k, v) in self._headers:
if (k.lower() == name):
return v
return default
|
'Return a list of all the header field names.
These will be sorted in the order they appeared in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.'
| def keys(self):
| return [k for (k, v) in self._headers]
|
'Return a list of all header values.
These will be sorted in the order they appeared in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.'
| def values(self):
| return [v for (k, v) in self._headers]
|
'Get all the header fields and values.
These will be sorted in the order they were in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.'
| def items(self):
| return self._headers[:]
|
'str() returns the formatted headers, complete with end line,
suitable for direct HTTP transmission.'
| def __str__(self):
| return '\r\n'.join(([('%s: %s' % kv) for kv in self._headers] + ['', '']))
|
'Return first matching header value for \'name\', or \'value\'
If there is no header named \'name\', add a new header with name \'name\'
and value \'value\'.'
| def setdefault(self, name, value):
| result = self.get(name)
if (result is None):
self._headers.append((self._convert_string_type(name), self._convert_string_type(value)))
return value
else:
return result
|
'Extended header setting.
_name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added.
Example:
h.add_header(\... | def add_header(self, _name, _value, **_params):
| parts = []
if (_value is not None):
_value = self._convert_string_type(_value)
parts.append(_value)
for (k, v) in _params.items():
k = self._convert_string_type(k)
if (v is None):
parts.append(k.replace('_', '-'))
else:
v = self._convert_string... |
'Invoke the application'
| def run(self, application):
| try:
self.setup_environ()
self.result = application(self.environ, self.start_response)
self.finish_response()
except:
try:
self.handle_error()
except:
self.close()
raise
|
'Set up the environment for one request'
| def setup_environ(self):
| env = self.environ = self.os_environ.copy()
self.add_cgi_vars()
env['wsgi.input'] = self.get_stdin()
env['wsgi.errors'] = self.get_stderr()
env['wsgi.version'] = self.wsgi_version
env['wsgi.run_once'] = self.wsgi_run_once
env['wsgi.url_scheme'] = self.get_scheme()
env['wsgi.multithread']... |
'Send any iterable data, then close self and the iterable
Subclasses intended for use in asynchronous servers will
want to redefine this method, such that it sets up callbacks
in the event loop to iterate over the data, and to call
\'self.close()\' once the response is finished.'
| def finish_response(self):
| try:
if ((not self.result_is_file()) or (not self.sendfile())):
for data in self.result:
self.write(data)
self.finish_content()
finally:
self.close()
|
'Return the URL scheme being used'
| def get_scheme(self):
| return guess_scheme(self.environ)
|
'Compute Content-Length or switch to chunked encoding if possible'
| def set_content_length(self):
| try:
blocks = len(self.result)
except (TypeError, AttributeError, NotImplementedError):
pass
else:
if (blocks == 1):
self.headers['Content-Length'] = str(self.bytes_sent)
return
|
'Make any necessary header changes or defaults
Subclasses can extend this to add other defaults.'
| def cleanup_headers(self):
| if ('Content-Length' not in self.headers):
self.set_content_length()
|
'\'start_response()\' callable as specified by PEP 3333'
| def start_response(self, status, headers, exc_info=None):
| if exc_info:
try:
if self.headers_sent:
raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
finally:
exc_info = None
elif (self.headers is not None):
raise AssertionError('Headers already set!')
self.status = status
self.header... |
'Convert/check value type.'
| def _convert_string_type(self, value, title):
| if (type(value) is str):
return value
raise AssertionError('{0} must be of type str (got {1})'.format(title, repr(value)))
|
'Transmit version/status/date/server, via self._write()'
| def send_preamble(self):
| if self.origin_server:
if self.client_is_modern():
self._write(('HTTP/%s %s\r\n' % (self.http_version, self.status)).encode('iso-8859-1'))
if ('Date' not in self.headers):
self._write(('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1'))
... |
'\'write()\' callable as specified by PEP 3333'
| def write(self, data):
| assert (type(data) is bytes), 'write() argument must be a bytes instance'
if (not self.status):
raise AssertionError('write() before start_response()')
elif (not self.headers_sent):
self.bytes_sent = len(data)
self.send_headers()
else:
self.bytes_s... |
'Platform-specific file transmission
Override this method in subclasses to support platform-specific
file transmission. It is only called if the application\'s
return iterable (\'self.result\') is an instance of
\'self.wsgi_file_wrapper\'.
This method should return a true value if it was able to actually
transmit the ... | def sendfile(self):
| return False
|
'Ensure headers and content have both been sent'
| def finish_content(self):
| if (not self.headers_sent):
self.headers.setdefault('Content-Length', '0')
self.send_headers()
else:
pass
|
'Close the iterable (if needed) and reset all instance vars
Subclasses may want to also drop the client connection.'
| def close(self):
| try:
if hasattr(self.result, 'close'):
self.result.close()
finally:
self.result = self.headers = self.status = self.environ = None
self.bytes_sent = 0
self.headers_sent = False
|
'Transmit headers to the client, via self._write()'
| def send_headers(self):
| self.cleanup_headers()
self.headers_sent = True
if ((not self.origin_server) or self.client_is_modern()):
self.send_preamble()
self._write(bytes(self.headers))
|
'True if \'self.result\' is an instance of \'self.wsgi_file_wrapper\''
| def result_is_file(self):
| wrapper = self.wsgi_file_wrapper
return ((wrapper is not None) and isinstance(self.result, wrapper))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.