code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def __init__(self, type=None, content=None, name=None): """ Initializer. Takes optional type, content, and name. The type, if given must be a token type (< 256). If not given, this matches any *leaf* node; the content may still be required. The content, if given, must be a string. If a name is given, the matching node is stored in the results dict under that key. """ if type is not None: assert 0 <= type < 256, type if content is not None: assert isinstance(content, basestring), repr(content) self.type = type self.content = content self.name = name
Initializer. Takes optional type, content, and name. The type, if given must be a token type (< 256). If not given, this matches any *leaf* node; the content may still be required. The content, if given, must be a string. If a name is given, the matching node is stored in the results dict under that key.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def match(self, node, results=None): """Override match() to insist on a leaf node.""" if not isinstance(node, Leaf): return False return BasePattern.match(self, node, results)
Override match() to insist on a leaf node.
match
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def __init__(self, type=None, content=None, name=None): """ Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or not), except if content is not None, in which it only matches non-leaf nodes that also match the content pattern. The content, if not None, must be a sequence of Patterns that must match the node's children exactly. If the content is given, the type must not be None. If a name is given, the matching node is stored in the results dict under that key. """ if type is not None: assert type >= 256, type if content is not None: assert not isinstance(content, basestring), repr(content) content = list(content) for i, item in enumerate(content): assert isinstance(item, BasePattern), (i, item) if isinstance(item, WildcardPattern): self.wildcards = True self.type = type self.content = content self.name = name
Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or not), except if content is not None, in which it only matches non-leaf nodes that also match the content pattern. The content, if not None, must be a sequence of Patterns that must match the node's children exactly. If the content is given, the type must not be None. If a name is given, the matching node is stored in the results dict under that key.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def _submatch(self, node, results=None): """ Match the pattern's content to the node's children. This assumes the node type matches and self.content is not None. Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. When returning False, the results dict may still be updated. """ if self.wildcards: for c, r in generate_matches(self.content, node.children): if c == len(node.children): if results is not None: results.update(r) return True return False if len(self.content) != len(node.children): return False for subpattern, child in zip(self.content, node.children): if not subpattern.match(child, results): return False return True
Match the pattern's content to the node's children. This assumes the node type matches and self.content is not None. Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. When returning False, the results dict may still be updated.
_submatch
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def __init__(self, content=None, min=0, max=HUGE, name=None): """ Initializer. Args: content: optional sequence of subsequences of patterns; if absent, matches one node; if present, each subsequence is an alternative [*] min: optional minimum number of times to match, default 0 max: optional maximum number of times to match, default HUGE name: optional name assigned to this match [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is equivalent to (a b c | d e | f g h); if content is None, this is equivalent to '.' in regular expression terms. The min and max parameters work as follows: min=0, max=maxint: .* min=1, max=maxint: .+ min=0, max=1: .? min=1, max=1: . If content is not None, replace the dot with the parenthesized list of alternatives, e.g. (a b c | d e | f g h)* """ assert 0 <= min <= max <= HUGE, (min, max) if content is not None: content = tuple(map(tuple, content)) # Protect against alterations # Check sanity of alternatives assert len(content), repr(content) # Can't have zero alternatives for alt in content: assert len(alt), repr(alt) # Can have empty alternatives self.content = content self.min = min self.max = max self.name = name
Initializer. Args: content: optional sequence of subsequences of patterns; if absent, matches one node; if present, each subsequence is an alternative [*] min: optional minimum number of times to match, default 0 max: optional maximum number of times to match, default HUGE name: optional name assigned to this match [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is equivalent to (a b c | d e | f g h); if content is None, this is equivalent to '.' in regular expression terms. The min and max parameters work as follows: min=0, max=maxint: .* min=1, max=maxint: .+ min=0, max=1: .? min=1, max=1: . If content is not None, replace the dot with the parenthesized list of alternatives, e.g. (a b c | d e | f g h)*
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def match_seq(self, nodes, results=None): """Does this pattern exactly match a sequence of nodes?""" for c, r in self.generate_matches(nodes): if c == len(nodes): if results is not None: results.update(r) if self.name: results[self.name] = list(nodes) return True return False
Does this pattern exactly match a sequence of nodes?
match_seq
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def generate_matches(self, nodes): """ Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches. """ if self.content is None: # Shortcut for special case (see __init__.__doc__) for count in xrange(self.min, 1 + min(len(nodes), self.max)): r = {} if self.name: r[self.name] = nodes[:count] yield count, r elif self.name == "bare_name": yield self._bare_name_matches(nodes) else: # The reason for this is that hitting the recursion limit usually # results in some ugly messages about how RuntimeErrors are being # ignored. We don't do this on non-CPython implementation because # they don't have this problem. if hasattr(sys, "getrefcount"): save_stderr = sys.stderr sys.stderr = StringIO() try: for count, r in self._recursive_matches(nodes, 0): if self.name: r[self.name] = nodes[:count] yield count, r except RuntimeError: # We fall back to the iterative pattern matching scheme if the recursive # scheme hits the recursion limit. for count, r in self._iterative_matches(nodes): if self.name: r[self.name] = nodes[:count] yield count, r finally: if hasattr(sys, "getrefcount"): sys.stderr = save_stderr
Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches.
generate_matches
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def _iterative_matches(self, nodes): """Helper to iteratively yield the matches.""" nodelen = len(nodes) if 0 >= self.min: yield 0, {} results = [] # generate matches that use just one alt from self.content for alt in self.content: for c, r in generate_matches(alt, nodes): yield c, r results.append((c, r)) # for each match, iterate down the nodes while results: new_results = [] for c0, r0 in results: # stop if the entire set of nodes has been matched if c0 < nodelen and c0 <= self.max: for alt in self.content: for c1, r1 in generate_matches(alt, nodes[c0:]): if c1 > 0: r = {} r.update(r0) r.update(r1) yield c0 + c1, r new_results.append((c0 + c1, r)) results = new_results
Helper to iteratively yield the matches.
_iterative_matches
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def _recursive_matches(self, nodes, count): """Helper to recursively yield the matches.""" assert self.content is not None if count >= self.min: yield 0, {} if count < self.max: for alt in self.content: for c0, r0 in generate_matches(alt, nodes): for c1, r1 in self._recursive_matches(nodes[c0:], count+1): r = {} r.update(r0) r.update(r1) yield c0 + c1, r
Helper to recursively yield the matches.
_recursive_matches
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def __init__(self, content=None): """ Initializer. The argument is either a pattern or None. If it is None, this only matches an empty sequence (effectively '$' in regex lingo). If it is not None, this matches whenever the argument pattern doesn't have any matches. """ if content is not None: assert isinstance(content, BasePattern), repr(content) self.content = content
Initializer. The argument is either a pattern or None. If it is None, this only matches an empty sequence (effectively '$' in regex lingo). If it is not None, this matches whenever the argument pattern doesn't have any matches.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def generate_matches(patterns, nodes): """ Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches. """ if not patterns: yield 0, {} else: p, rest = patterns[0], patterns[1:] for c0, r0 in p.generate_matches(nodes): if not rest: yield c0, r0 else: for c1, r1 in generate_matches(rest, nodes[c0:]): r = {} r.update(r0) r.update(r1) yield c0 + c1, r
Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches.
generate_matches
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pytree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pytree.py
MIT
def get_all_fix_names(fixer_pkg, remove_prefix=True): """Return a sorted list of all available fix names in the given package.""" pkg = __import__(fixer_pkg, [], [], ["*"]) fixer_dir = os.path.dirname(pkg.__file__) fix_names = [] for name in sorted(os.listdir(fixer_dir)): if name.startswith("fix_") and name.endswith(".py"): if remove_prefix: name = name[4:] fix_names.append(name[:-3]) return fix_names
Return a sorted list of all available fix names in the given package.
get_all_fix_names
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def _get_head_types(pat): """ Accepts a pytree Pattern Node and returns a set of the pattern types which will match first. """ if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)): # NodePatters must either have no type and no content # or a type and content -- so they don't get any farther # Always return leafs if pat.type is None: raise _EveryNode return set([pat.type]) if isinstance(pat, pytree.NegatedPattern): if pat.content: return _get_head_types(pat.content) raise _EveryNode # Negated Patterns don't have a type if isinstance(pat, pytree.WildcardPattern): # Recurse on each node in content r = set() for p in pat.content: for x in p: r.update(_get_head_types(x)) return r raise Exception("Oh no! I don't understand pattern %s" %(pat))
Accepts a pytree Pattern Node and returns a set of the pattern types which will match first.
_get_head_types
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def _get_headnode_dict(fixer_list): """ Accepts a list of fixers and returns a dictionary of head node type --> fixer list. """ head_nodes = collections.defaultdict(list) every = [] for fixer in fixer_list: if fixer.pattern: try: heads = _get_head_types(fixer.pattern) except _EveryNode: every.append(fixer) else: for node_type in heads: head_nodes[node_type].append(fixer) else: if fixer._accept_type is not None: head_nodes[fixer._accept_type].append(fixer) else: every.append(fixer) for node_type in chain(pygram.python_grammar.symbol2number.itervalues(), pygram.python_grammar.tokens): head_nodes[node_type].extend(every) return dict(head_nodes)
Accepts a list of fixers and returns a dictionary of head node type --> fixer list.
_get_headnode_dict
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def get_fixers_from_package(pkg_name): """ Return the fully qualified names for fixers in the package pkg_name. """ return [pkg_name + "." + fix_name for fix_name in get_all_fix_names(pkg_name, False)]
Return the fully qualified names for fixers in the package pkg_name.
get_fixers_from_package
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def __init__(self, fixer_names, options=None, explicit=None): """Initializer. Args: fixer_names: a list of fixers to import options: a dict with configuration. explicit: a list of fixers to run even if they are explicit. """ 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 = pygram.python_grammar # When this is True, the refactor*() methods will call write_file() for # files processed even if they were not changed during refactoring. If # and only if the refactor method's write parameter was True. self.write_unchanged_files = self.options.get("write_unchanged_files") self.errors = [] self.logger = logging.getLogger("RefactoringTool") self.fixer_log = [] self.wrote = False self.driver = driver.Driver(self.grammar, convert=pytree.convert, logger=self.logger) self.pre_order, self.post_order = self.get_fixers() self.files = [] # List of files that were or should be modified self.BM = bm.BottomMatcher() self.bmi_pre_order = [] # Bottom Matcher incompatible fixers self.bmi_post_order = [] for fixer in chain(self.post_order, self.pre_order): if fixer.BM_compatible: self.BM.add_fixer(fixer) # remove fixers that will be handled by the bottom-up # matcher elif fixer in self.pre_order: self.bmi_pre_order.append(fixer) elif fixer in self.post_order: self.bmi_post_order.append(fixer) self.bmi_pre_order_heads = _get_headnode_dict(self.bmi_pre_order) self.bmi_post_order_heads = _get_headnode_dict(self.bmi_post_order)
Initializer. Args: fixer_names: a list of fixers to import options: a dict with configuration. explicit: a list of fixers to run even if they are explicit.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def get_fixers(self): """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. """ 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 = fix_name.split("_") class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts]) try: fix_class = getattr(mod, class_name) except AttributeError: raise FixerError("Can't find %s.%s" % (fix_name, class_name)) fixer = fix_class(self.options, self.fixer_log) if fixer.explicit and self.explicit is not True and \ fix_mod_path not in self.explicit: self.log_message("Skipping optional fixer: %s", fix_name) continue self.log_debug("Adding transformation: %s", fix_name) if fixer.order == "pre": pre_order_fixers.append(fixer) elif fixer.order == "post": post_order_fixers.append(fixer) else: raise FixerError("Illegal fixer order: %r" % fixer.order) key_func = operator.attrgetter("run_order") pre_order_fixers.sort(key=key_func) post_order_fixers.sort(key=key_func) return (pre_order_fixers, post_order_fixers)
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.
get_fixers
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def refactor(self, items, write=False, doctests_only=False): """Refactor a list of files and directories.""" 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)
Refactor a list of files and directories.
refactor
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def refactor_dir(self, dir_name, write=False, doctests_only=False): """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. """ 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): fullname = os.path.join(dirpath, name) self.refactor_file(fullname, write, doctests_only) # Modify dirnames in-place to remove subdirs with leading dots dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
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.
refactor_dir
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def _read_python_source(self, filename): """ Do our best to decode a Python source file correctly. """ try: f = open(filename, "rb") except IOError 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=encoding) as f: return _from_system_newlines(f.read()), encoding
Do our best to decode a Python source file correctly.
_read_python_source
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def refactor_string(self, data, name): """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. """ 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__.__name__, err) return finally: self.driver.grammar = self.grammar tree.future_features = features self.log_debug("Refactoring %s", name) self.refactor_tree(tree, name) return tree
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.
refactor_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def refactor_tree(self, tree, name): """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 the tree was modified, False otherwise. """ for fixer in chain(self.pre_order, self.post_order): fixer.start_tree(tree, name) #use traditional matching for the incompatible fixers self.traverse_by(self.bmi_pre_order_heads, tree.pre_order()) self.traverse_by(self.bmi_post_order_heads, tree.post_order()) # obtain a set of candidate nodes match_set = self.BM.run(tree.leaves()) while any(match_set.values()): for fixer in self.BM.fixers: if fixer in match_set and match_set[fixer]: #sort by depth; apply fixers from bottom(of the AST) to top match_set[fixer].sort(key=pytree.Base.depth, reverse=True) if fixer.keep_line_order: #some fixers(eg fix_imports) must be applied #with the original file's line order match_set[fixer].sort(key=pytree.Base.get_lineno) for node in list(match_set[fixer]): if node in match_set[fixer]: match_set[fixer].remove(node) try: find_root(node) except ValueError: # this node has been cut off from a # previous transformation ; skip continue if node.fixers_applied and fixer in node.fixers_applied: # do not apply the same fixer again continue results = fixer.match(node) if results: new = fixer.transform(node, results) if new is not None: node.replace(new) #new.fixers_applied.append(fixer) for node in new.post_order(): # do not apply the fixer again to # this or any subnode if not node.fixers_applied: node.fixers_applied = [] node.fixers_applied.append(fixer) # update the original match set for # the added code new_matches = self.BM.run(new.leaves()) for fxr in new_matches: if not fxr in match_set: match_set[fxr]=[] match_set[fxr].extend(new_matches[fxr]) for fixer in chain(self.pre_order, self.post_order): fixer.finish_tree(tree, name) return tree.was_changed
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 the tree was modified, False otherwise.
refactor_tree
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def traverse_by(self, fixers, traversal): """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 """ 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 = new
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
traverse_by
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def processed_file(self, new_text, filename, old_text=None, write=False, encoding=None): """ Called when a file has been refactored and there may be changes. """ 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 %s", filename) if not self.write_unchanged_files: return if write: self.write_file(new_text, filename, old_text, encoding) else: self.log_debug("Not writing changes to %s", filename)
Called when a file has been refactored and there may be changes.
processed_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def write_file(self, new_text, filename, old_text, encoding=None): """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. """ try: f = _open_with_encoding(filename, "w", encoding=encoding) except os.error as err: self.log_error("Can't create %s: %s", filename, err) return try: f.write(_to_system_newlines(new_text)) except os.error as err: self.log_error("Can't write %s: %s", filename, err) finally: f.close() self.log_debug("Wrote changes to %s", filename) self.wrote = True
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.
write_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def refactor_docstring(self, input, filename): """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, like most parsers, it is not geared towards preserving the original source.) """ result = [] block = None block_lineno = None indent = None lineno = 0 for line in input.splitlines(True): lineno += 1 if line.lstrip().startswith(self.PS1): if block is not None: result.extend(self.refactor_doctest(block, block_lineno, indent, filename)) block_lineno = lineno block = [line] i = line.find(self.PS1) indent = line[:i] elif (indent is not None and (line.startswith(indent + self.PS2) or line == indent + self.PS2.rstrip() + u"\n")): block.append(line) else: if block is not None: result.extend(self.refactor_doctest(block, block_lineno, indent, filename)) block = None indent = None result.append(line) if block is not None: result.extend(self.refactor_doctest(block, block_lineno, indent, filename)) return u"".join(result)
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, like most parsers, it is not geared towards preserving the original source.)
refactor_docstring
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def refactor_doctest(self, block, lineno, indent, filename): """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). """ 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(u"\n")) self.log_error("Can't parse docstring in %s line %s: %s: %s", filename, lineno, err.__class__.__name__, err) return block if self.refactor_tree(tree, filename): new = unicode(tree).splitlines(True) # Undo the adjustment of the line numbers in wrap_toks() below. clipped, new = new[:lineno-1], new[lineno-1:] assert clipped == [u"\n"] * (lineno-1), clipped if not new[-1].endswith(u"\n"): new[-1] += u"\n" block = [indent + self.PS1 + new.pop(0)] if new: block += [indent + self.PS2 + line for line in new] return block
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).
refactor_doctest
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def parse_block(self, block, lineno, indent): """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. """ tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) tree.future_features = frozenset() return tree
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.
parse_block
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def wrap_toks(self, block, lineno, indent): """Wraps a tokenize stream to systematically modify start/end.""" 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 # Don't bother updating the columns; this is too complicated # since line_text would also have to be updated and it would # still break for tokens spanning lines. Let the user guess # that the column numbers for doctests are relative to the # end of the prompt string (PS1 or PS2). yield type, value, (line0, col0), (line1, col1), line_text
Wraps a tokenize stream to systematically modify start/end.
wrap_toks
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def gen_lines(self, block, indent): """Generates lines as expected by tokenize from a list of lines. This strips the first len(indent + self.PS1) characters off each line. """ 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() + u"\n": yield u"\n" else: raise AssertionError("line=%r, prefix=%r" % (line, prefix)) prefix = prefix2 while True: yield ""
Generates lines as expected by tokenize from a list of lines. This strips the first len(indent + self.PS1) characters off each line.
gen_lines
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/refactor.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/refactor.py
MIT
def traverse_imports(names): """ Walks over all the names imported in a dotted_as_names node. """ pending = [names] while pending: node = pending.pop() if node.type == token.NAME: yield node.value elif node.type == syms.dotted_name: yield "".join([ch.value for ch in node.children]) elif node.type == syms.dotted_as_name: pending.append(node.children[0]) elif node.type == syms.dotted_as_names: pending.extend(node.children[::-2]) else: raise AssertionError("unknown node type")
Walks over all the names imported in a dotted_as_names node.
traverse_imports
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/fixes/fix_import.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/fixes/fix_import.py
MIT
def has_metaclass(parent): """ we have to check the cls_node without changing it. There are two possibilities: 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta') 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta') """ for node in parent.children: if node.type == syms.suite: return has_metaclass(node) elif node.type == syms.simple_stmt and node.children: expr_node = node.children[0] if expr_node.type == syms.expr_stmt and expr_node.children: left_side = expr_node.children[0] if isinstance(left_side, Leaf) and \ left_side.value == '__metaclass__': return True return False
we have to check the cls_node without changing it. There are two possibilities: 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta') 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta')
has_metaclass
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/fixes/fix_metaclass.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/fixes/fix_metaclass.py
MIT
def fixup_parse_tree(cls_node): """ one-line classes don't get a suite in the parse tree so we add one to normalize the tree """ for node in cls_node.children: if node.type == syms.suite: # already in the preferred format, do nothing return # !%@#! oneliners have no suite node, we have to fake one up for i, node in enumerate(cls_node.children): if node.type == token.COLON: break else: raise ValueError("No class suite and no ':'!") # move everything into a suite node suite = Node(syms.suite, []) while cls_node.children[i+1:]: move_node = cls_node.children[i+1] suite.append_child(move_node.clone()) move_node.remove() cls_node.append_child(suite) node = suite
one-line classes don't get a suite in the parse tree so we add one to normalize the tree
fixup_parse_tree
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/fixes/fix_metaclass.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/fixes/fix_metaclass.py
MIT
def fixup_simple_stmt(parent, i, stmt_node): """ if there is a semi-colon all the parts count as part of the same simple_stmt. We just want the __metaclass__ part so we move everything after the semi-colon into its own simple_stmt node """ for semi_ind, node in enumerate(stmt_node.children): if node.type == token.SEMI: # *sigh* break else: return node.remove() # kill the semicolon new_expr = Node(syms.expr_stmt, []) new_stmt = Node(syms.simple_stmt, [new_expr]) while stmt_node.children[semi_ind:]: move_node = stmt_node.children[semi_ind] new_expr.append_child(move_node.clone()) move_node.remove() parent.insert_child(i, new_stmt) new_leaf1 = new_stmt.children[0].children[0] old_leaf1 = stmt_node.children[0].children[0] new_leaf1.prefix = old_leaf1.prefix
if there is a semi-colon all the parts count as part of the same simple_stmt. We just want the __metaclass__ part so we move everything after the semi-colon into its own simple_stmt node
fixup_simple_stmt
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/fixes/fix_metaclass.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/fixes/fix_metaclass.py
MIT
def fixup_indent(suite): """ If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start """ kids = suite.children[::-1] # find the first indent while kids: node = kids.pop() if node.type == token.INDENT: break # find the first Leaf while kids: node = kids.pop() if isinstance(node, Leaf) and node.type != token.DEDENT: if node.prefix: node.prefix = u'' return else: kids.extend(node.children[::-1])
If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start
fixup_indent
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/fixes/fix_metaclass.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/fixes/fix_metaclass.py
MIT
def transform_import(self, node, results): """Transform for the basic import case. Replaces the old import name with a comma separated list of its replacements. """ import_mod = results.get("module") pref = import_mod.prefix names = [] # create a Node list of the replacement modules 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 the basic import case. Replaces the old import name with a comma separated list of its replacements.
transform_import
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/fixes/fix_urllib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/fixes/fix_urllib.py
MIT
def transform_member(self, node, results): """Transform for imports of specific module elements. Replaces the module to be imported from with the appropriate new module. """ mod_member = results.get("mod_member") pref = mod_member.prefix member = results.get("member") # Simple case with only a single member being imported if member: # this may be a list of length one, or just a node if isinstance(member, list): member = member[0] new_name = None for change in MAPPING[mod_member.value]: if member.value in change[1]: new_name = change[0] break if new_name: mod_member.replace(Name(new_name, prefix=pref)) else: self.cannot_convert(node, "This is an invalid module element") # Multiple members being imported else: # a dictionary for replacements, order matters modules = [] mod_dict = {} members = results["members"] for member in members: # we only care about the actual members if member.type == syms.import_as_name: as_name = member.children[2].value member_name = member.children[0].value else: member_name = member.value as_name = None if member_name != u",": for change in MAPPING[mod_member.value]: if member_name in change[1]: if change[0] not in mod_dict: modules.append(change[0]) mod_dict.setdefault(change[0], []).append(member) new_nodes = [] indentation = find_indentation(node) first = True def handle_name(name, prefix): if name.type == syms.import_as_name: kids = [Name(name.children[0].value, prefix=prefix), name.children[1].clone(), name.children[2].clone()] return [Node(syms.import_as_name, kids)] return [Name(name.value, prefix=prefix)] for module in modules: elts = mod_dict[module] names = [] for elt in elts[:-1]: names.extend(handle_name(elt, pref)) names.append(Comma()) names.extend(handle_name(elts[-1], pref)) new = FromImport(module, names) if not first or node.parent.prefix.endswith(indentation): new.prefix = indentation new_nodes.append(new) first = False if new_nodes: nodes = [] for new_node in new_nodes[:-1]: nodes.extend([new_node, Newline()]) nodes.append(new_nodes[-1]) node.replace(nodes) else: self.cannot_convert(node, "All module elements are invalid")
Transform for imports of specific module elements. Replaces the module to be imported from with the appropriate new module.
transform_member
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/fixes/fix_urllib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/fixes/fix_urllib.py
MIT
def transform_dot(self, node, results): """Transform for calls to module members in code.""" 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: module_dot.replace(Name(new_name, prefix=module_dot.prefix)) else: self.cannot_convert(node, "This is an invalid module element")
Transform for calls to module members in code.
transform_dot
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/fixes/fix_urllib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/fixes/fix_urllib.py
MIT
def parse_graminit_h(self, filename): """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. """ try: f = open(filename) except IOError, 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(r"^#define\s+(\w+)\s+(\d+)$", line) if not mo and line.strip(): print "%s(%s): can't parse %s" % (filename, lineno, line.strip()) else: symbol, number = mo.groups() number = int(number) assert symbol not in self.symbol2number assert number not in self.number2symbol self.symbol2number[symbol] = number self.number2symbol[number] = symbol return True
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.
parse_graminit_h
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/conv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/conv.py
MIT
def parse_graminit_c(self, filename): """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 definition has the following form: - one or more arc arrays, each of the form: static arc arcs_<n>_<m>[<k>] = { {<i>, <j>}, ... }; - followed by a state array, of the form: static state states_<s>[<t>] = { {<k>, arcs_<n>_<m>}, ... }; """ try: f = open(filename) except IOError, err: print "Can't open %s: %s" % (filename, err) return False # The code below essentially uses f's iterator-ness! lineno = 0 # Expect the two #include lines lineno, line = lineno+1, f.next() assert line == '#include "pgenheaders.h"\n', (lineno, line) lineno, line = lineno+1, f.next() assert line == '#include "grammar.h"\n', (lineno, line) # Parse the state definitions lineno, line = lineno+1, f.next() allarcs = {} states = [] while line.startswith("static arc "): while line.startswith("static arc "): mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$", line) assert mo, (lineno, line) n, m, k = map(int, mo.groups()) arcs = [] for _ in range(k): lineno, line = lineno+1, f.next() mo = re.match(r"\s+{(\d+), (\d+)},$", line) assert mo, (lineno, line) i, j = map(int, mo.groups()) arcs.append((i, j)) lineno, line = lineno+1, f.next() assert line == "};\n", (lineno, line) allarcs[(n, m)] = arcs lineno, line = lineno+1, f.next() mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line) assert mo, (lineno, line) s, t = map(int, mo.groups()) assert s == len(states), (lineno, line) state = [] for _ in range(t): lineno, line = lineno+1, f.next() mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line) assert mo, (lineno, line) k, n, m = map(int, mo.groups()) arcs = allarcs[n, m] assert k == len(arcs), (lineno, line) state.append(arcs) states.append(state) lineno, line = lineno+1, f.next() assert line == "};\n", (lineno, line) lineno, line = lineno+1, f.next() self.states = states # Parse the dfas dfas = {} mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line) assert mo, (lineno, line) ndfas = int(mo.group(1)) for i in range(ndfas): lineno, line = lineno+1, f.next() mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$', line) assert mo, (lineno, line) symbol = mo.group(2) number, x, y, z = map(int, mo.group(1, 3, 4, 5)) assert self.symbol2number[symbol] == number, (lineno, line) assert self.number2symbol[number] == symbol, (lineno, line) assert x == 0, (lineno, line) state = states[z] assert y == len(state), (lineno, line) lineno, line = lineno+1, f.next() mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line) assert mo, (lineno, line) first = {} rawbitset = eval(mo.group(1)) for i, c in enumerate(rawbitset): byte = ord(c) for j in range(8): if byte & (1<<j): first[i*8 + j] = 1 dfas[number] = (state, first) lineno, line = lineno+1, f.next() assert line == "};\n", (lineno, line) self.dfas = dfas # Parse the labels labels = [] lineno, line = lineno+1, f.next() mo = re.match(r"static label labels\[(\d+)\] = {$", line) assert mo, (lineno, line) nlabels = int(mo.group(1)) for i in range(nlabels): lineno, line = lineno+1, f.next() mo = re.match(r'\s+{(\d+), (0|"\w+")},$', line) assert mo, (lineno, line) x, y = mo.groups() x = int(x) if y == "0": y = None else: y = eval(y) labels.append((x, y)) lineno, line = lineno+1, f.next() assert line == "};\n", (lineno, line) self.labels = labels # Parse the grammar struct lineno, line = lineno+1, f.next() assert line == "grammar _PyParser_Grammar = {\n", (lineno, line) lineno, line = lineno+1, f.next() mo = re.match(r"\s+(\d+),$", line) assert mo, (lineno, line) ndfas = int(mo.group(1)) assert ndfas == len(self.dfas) lineno, line = lineno+1, f.next() assert line == "\tdfas,\n", (lineno, line) lineno, line = lineno+1, f.next() mo = re.match(r"\s+{(\d+), labels},$", line) assert mo, (lineno, line) nlabels = int(mo.group(1)) assert nlabels == len(self.labels), (lineno, line) lineno, line = lineno+1, f.next() mo = re.match(r"\s+(\d+)$", line) assert mo, (lineno, line) start = int(mo.group(1)) assert start in self.number2symbol, (lineno, line) self.start = start lineno, line = lineno+1, f.next() assert line == "};\n", (lineno, line) try: lineno, line = lineno+1, f.next() except StopIteration: pass else: assert 0, (lineno, 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 definition has the following form: - one or more arc arrays, each of the form: static arc arcs_<n>_<m>[<k>] = { {<i>, <j>}, ... }; - followed by a state array, of the form: static state states_<s>[<t>] = { {<k>, arcs_<n>_<m>}, ... };
parse_graminit_c
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/conv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/conv.py
MIT
def parse_tokens(self, tokens, debug=False): """Parse a series of tokens and return the syntax tree.""" # XXX Move the prefix computation into a wrapper around tokenize. p = parse.Parser(self.grammar, self.convert) p.setup() lineno = 1 column = 0 type = value = start = end = line_text = None prefix = u"" for quintuple in tokens: type, value, start, end, line_text = quintuple if start != (lineno, column): assert (lineno, column) <= start, ((lineno, column), start) s_lineno, s_column = start if lineno < s_lineno: prefix += "\n" * (s_lineno - lineno) lineno = s_lineno column = 0 if column < s_column: prefix += line_text[column:s_column] column = s_column if type in (tokenize.COMMENT, tokenize.NL): prefix += value lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 continue if type == token.OP: type = grammar.opmap[value] if debug: self.logger.debug("%s %r (prefix=%r)", token.tok_name[type], value, prefix) if p.addtoken(type, value, (prefix, start)): if debug: self.logger.debug("Stop.") break prefix = "" lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 else: # We never broke out -- EOF is too soon (how can this happen???) raise parse.ParseError("incomplete input", type, value, (prefix, start)) return p.rootnode
Parse a series of tokens and return the syntax tree.
parse_tokens
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/driver.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/driver.py
MIT
def parse_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree.""" tokens = tokenize.generate_tokens(stream.readline) return self.parse_tokens(tokens, debug)
Parse a stream and return the syntax tree.
parse_stream_raw
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/driver.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/driver.py
MIT
def parse_file(self, filename, encoding=None, debug=False): """Parse a file and return the syntax tree.""" stream = codecs.open(filename, "r", encoding) try: return self.parse_stream(stream, debug) finally: stream.close()
Parse a file and return the syntax tree.
parse_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/driver.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/driver.py
MIT
def parse_string(self, text, debug=False): """Parse a string and return the syntax tree.""" tokens = tokenize.generate_tokens(StringIO.StringIO(text).readline) return self.parse_tokens(tokens, debug)
Parse a string and return the syntax tree.
parse_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/driver.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/driver.py
MIT
def load_grammar(gt="Grammar.txt", gp=None, save=True, force=False, logger=None): """Load the grammar (maybe from a pickle).""" if logger is None: logger = logging.getLogger() if gp is None: head, tail = os.path.splitext(gt) if tail == ".txt": tail = "" gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle" if force or not _newer(gp, gt): logger.info("Generating grammar tables from %s", gt) g = pgen.generate_grammar(gt) if save: logger.info("Writing grammar tables to %s", gp) try: g.dump(gp) except IOError, e: logger.info("Writing failed:"+str(e)) else: g = grammar.Grammar() g.load(gp) return g
Load the grammar (maybe from a pickle).
load_grammar
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/driver.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/driver.py
MIT
def _newer(a, b): """Inquire whether file a was written since file b.""" if not os.path.exists(a): return False if not os.path.exists(b): return True return os.path.getmtime(a) >= os.path.getmtime(b)
Inquire whether file a was written since file b.
_newer
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/driver.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/driver.py
MIT
def main(*args): """Main program, when run as a script: produce grammar pickle files. Calls load_grammar for each argument, a path to a grammar text file. """ if not args: args = sys.argv[1:] logging.basicConfig(level=logging.INFO, stream=sys.stdout, format='%(message)s') for gt in args: load_grammar(gt, save=True, force=True) return True
Main program, when run as a script: produce grammar pickle files. Calls load_grammar for each argument, a path to a grammar text file.
main
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/driver.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/driver.py
MIT
def dump(self, filename): """Dump the grammar tables to a pickle file.""" f = open(filename, "wb") pickle.dump(self.__dict__, f, 2) f.close()
Dump the grammar tables to a pickle file.
dump
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/grammar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/grammar.py
MIT
def load(self, filename): """Load the grammar tables from a pickle file.""" f = open(filename, "rb") d = pickle.load(f) f.close() self.__dict__.update(d)
Load the grammar tables from a pickle file.
load
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/grammar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/grammar.py
MIT
def report(self): """Dump the grammar tables to standard output, for debugging.""" 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
Dump the grammar tables to standard output, for debugging.
report
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/grammar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/grammar.py
MIT
def __init__(self, grammar, convert=None): """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 not given, no conversion is done and the syntax tree produced is the concrete syntax tree. If given, it must be a function of two arguments, the first being the grammar (a grammar.Grammar instance), and the second being the concrete syntax tree node to be converted. The syntax tree is converted from the bottom up. A concrete syntax tree node is a (type, value, context, nodes) tuple, where type is the node type (a token or symbol number), value is None for symbols and a string for tokens, context is None or an opaque value used for error reporting (typically a (lineno, offset) pair), and nodes is a list of children for symbols, and None for tokens. An abstract syntax tree node may be anything; this is entirely up to the converter function. """ self.grammar = grammar self.convert = convert or (lambda grammar, node: node)
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 not given, no conversion is done and the syntax tree produced is the concrete syntax tree. If given, it must be a function of two arguments, the first being the grammar (a grammar.Grammar instance), and the second being the concrete syntax tree node to be converted. The syntax tree is converted from the bottom up. A concrete syntax tree node is a (type, value, context, nodes) tuple, where type is the node type (a token or symbol number), value is None for symbols and a string for tokens, context is None or an opaque value used for error reporting (typically a (lineno, offset) pair), and nodes is a list of children for symbols, and None for tokens. An abstract syntax tree node may be anything; this is entirely up to the converter function.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/parse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/parse.py
MIT
def setup(self, start=None): """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 (implicit or explicit) start symbol. """ if start is None: start = self.grammar.start # Each stack entry is a tuple: (dfa, state, node). # A node is a tuple: (type, value, context, children), # where children is a list of nodes or None, and context may be None. newnode = (start, None, None, []) stackentry = (self.grammar.dfas[start], 0, newnode) self.stack = [stackentry] self.rootnode = None self.used_names = set() # Aliased to self.rootnode.used_names in pop()
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 (implicit or explicit) start symbol.
setup
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/parse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/parse.py
MIT
def addtoken(self, type, value, context): """Add a token; return True iff this is the end of the program.""" # Map from token to label ilabel = self.classify(type, value, context) # Loop until the token is shifted; may raise exceptions while True: dfa, state, node = self.stack[-1] states, first = dfa arcs = states[state] # Look for a state with this label for i, newstate in arcs: t, v = self.grammar.labels[i] if ilabel == i: # Look it up in the list of labels assert t < 256 # Shift a token; we're done with it self.shift(type, value, newstate, context) # Pop while we are in an accept-only state state = newstate while states[state] == [(0, state)]: self.pop() if not self.stack: # Done parsing! return True dfa, state, node = self.stack[-1] states, first = dfa # Done with this token return False elif t >= 256: # See if it's a symbol and if we're in its first set itsdfa = self.grammar.dfas[t] itsstates, itsfirst = itsdfa if ilabel in itsfirst: # Push a symbol self.push(t, self.grammar.dfas[t], newstate, context) break # To continue the outer while loop else: if (0, state) in arcs: # An accepting state, pop it and try something else self.pop() if not self.stack: # Done parsing, but another token is input raise ParseError("too much input", type, value, context) else: # No success finding a transition raise ParseError("bad input", type, value, context)
Add a token; return True iff this is the end of the program.
addtoken
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/parse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/parse.py
MIT
def tokenize(readline, tokeneater=printtoken): """ The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens(). """ try: tokenize_loop(readline, tokeneater) except StopTokenizing: pass
The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens().
tokenize
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/tokenize.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/tokenize.py
MIT
def detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned. """ bom_found = False encoding = None default = 'utf-8' def read_or_stop(): try: return readline() except StopIteration: return bytes() def find_cookie(line): try: line_string = line.decode('ascii') except UnicodeDecodeError: return None match = cookie_re.match(line_string) if not match: return None encoding = _get_normal_name(match.group(1)) try: codec = lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter raise SyntaxError("unknown encoding: " + encoding) if bom_found: if codec.name != 'utf-8': # This behaviour mimics the Python interpreter raise SyntaxError('encoding problem: utf-8') encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] encoding = find_cookie(first) if encoding: return encoding, [first] if not blank_re.match(first): return default, [first] second = read_or_stop() if not second: return default, [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return default, [first, second]
The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned.
detect_encoding
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/tokenize.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/tokenize.py
MIT
def generate_tokens(readline): """ The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration: readline = open(myfile).next # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included. """ lnum = parenlev = continued = 0 namechars, numchars = string.ascii_letters + '_', '0123456789' contstr, needcont = '', 0 contline = None indents = [0] while 1: # loop over lines in stream try: line = readline() except StopIteration: line = '' lnum = lnum + 1 pos, max = 0, len(line) if contstr: # continued string if not line: raise TokenError, ("EOF in multi-line string", strstart) endmatch = endprog.match(line) if endmatch: pos = end = endmatch.end(0) yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line) contstr, needcont = '', 0 contline = None elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline) contstr = '' contline = None continue else: contstr = contstr + line contline = contline + line continue elif parenlev == 0 and not continued: # new statement if not line: break column = 0 while pos < max: # measure leading whitespace if line[pos] == ' ': column = column + 1 elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize elif line[pos] == '\f': column = 0 else: break pos = pos + 1 if pos == max: break if line[pos] in '#\r\n': # skip comments or blank lines if line[pos] == '#': comment_token = line[pos:].rstrip('\r\n') nl_pos = pos + len(comment_token) yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line) yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line) else: yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line) continue if column > indents[-1]: # count indents or dedents indents.append(column) yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line) while column < indents[-1]: if column not in indents: raise IndentationError( "unindent does not match any outer indentation level", ("<tokenize>", lnum, pos, line)) indents = indents[:-1] yield (DEDENT, '', (lnum, pos), (lnum, pos), line) else: # continued statement if not line: raise TokenError, ("EOF in multi-line statement", (lnum, 0)) continued = 0 while pos < max: pseudomatch = pseudoprog.match(line, pos) if pseudomatch: # scan for tokens start, end = pseudomatch.span(1) spos, epos, pos = (lnum, start), (lnum, end), end token, initial = line[start:end], line[start] if initial in numchars or \ (initial == '.' and token != '.'): # ordinary number yield (NUMBER, token, spos, epos, line) elif initial in '\r\n': newline = NEWLINE if parenlev > 0: newline = NL yield (newline, token, spos, epos, line) elif initial == '#': assert not token.endswith("\n") yield (COMMENT, token, spos, epos, line) elif token in triple_quoted: endprog = endprogs[token] endmatch = endprog.match(line, pos) if endmatch: # all on one line pos = endmatch.end(0) token = line[start:pos] yield (STRING, token, spos, (lnum, pos), line) else: strstart = (lnum, start) # multiple lines contstr = line[start:] contline = line break elif initial in single_quoted or \ token[:2] in single_quoted or \ token[:3] in single_quoted: if token[-1] == '\n': # continued string strstart = (lnum, start) endprog = (endprogs[initial] or endprogs[token[1]] or endprogs[token[2]]) contstr, needcont = line[start:], 1 contline = line break else: # ordinary string yield (STRING, token, spos, epos, line) elif initial in namechars: # ordinary name yield (NAME, token, spos, epos, line) elif initial == '\\': # continued stmt # This yield is new; needed for better idempotency: yield (NL, token, spos, (lnum, pos), line) continued = 1 else: if initial in '([{': parenlev = parenlev + 1 elif initial in ')]}': parenlev = parenlev - 1 yield (OP, token, spos, epos, line) else: yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos+1), line) pos = pos + 1 for indent in indents[1:]: # pop remaining indent levels yield (DEDENT, '', (lnum, 0), (lnum, 0), '') yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration: readline = open(myfile).next # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included.
generate_tokens
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/lib2to3/pgen2/tokenize.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib2to3/pgen2/tokenize.py
MIT
def fileConfig(fname, defaults=None, disable_existing_loggers=True): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). """ import ConfigParser cp = ConfigParser.ConfigParser(defaults) if hasattr(fname, 'readline'): cp.readfp(fname) else: cp.read(fname) formatters = _create_formatters(cp) # critical section logging._acquireLock() try: logging._handlers.clear() del logging._handlerList[:] # Handlers add themselves to logging._handlers handlers = _install_handlers(cp, formatters) _install_loggers(cp, handlers, disable_existing_loggers) finally: logging._releaseLock()
Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration).
fileConfig
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def _resolve(name): """Resolve a dotted name to a global object.""" name = name.split('.') used = name.pop(0) found = __import__(used) for n in name: used = used + '.' + n try: found = getattr(found, n) except AttributeError: __import__(used) found = getattr(found, n) return found
Resolve a dotted name to a global object.
_resolve
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def resolve(self, s): """ Resolve strings to objects using standard import and attribute syntax. """ name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag try: found = getattr(found, frag) except AttributeError: self.importer(used) found = getattr(found, frag) return found except ImportError: e, tb = sys.exc_info()[1:] v = ValueError('Cannot resolve %r: %s' % (s, e)) v.__cause__, v.__traceback__ = e, tb raise v
Resolve strings to objects using standard import and attribute syntax.
resolve
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def cfg_convert(self, value): """Default converter for the cfg:// protocol.""" rest = value m = self.WORD_PATTERN.match(rest) if m is None: raise ValueError("Unable to convert %r" % value) else: rest = rest[m.end():] d = self.config[m.groups()[0]] #print d, rest while rest: m = self.DOT_PATTERN.match(rest) if m: d = d[m.groups()[0]] else: m = self.INDEX_PATTERN.match(rest) if m: idx = m.groups()[0] if not self.DIGIT_PATTERN.match(idx): d = d[idx] else: try: n = int(idx) # try as number first (most likely) d = d[n] except TypeError: d = d[idx] if m: rest = rest[m.end():] else: raise ValueError('Unable to convert ' '%r at %r' % (value, rest)) #rest should be empty return d
Default converter for the cfg:// protocol.
cfg_convert
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def convert(self, value): """ Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. """ if not isinstance(value, ConvertingDict) and isinstance(value, dict): value = ConvertingDict(value) value.configurator = self elif not isinstance(value, ConvertingList) and isinstance(value, list): value = ConvertingList(value) value.configurator = self elif not isinstance(value, ConvertingTuple) and\ isinstance(value, tuple): value = ConvertingTuple(value) value.configurator = self elif isinstance(value, basestring): # str for py3k m = self.CONVERT_PATTERN.match(value) if m: d = m.groupdict() prefix = d['prefix'] converter = self.value_converters.get(prefix, None) if converter: suffix = d['suffix'] converter = getattr(self, converter) value = converter(suffix) return value
Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do.
convert
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def configure_custom(self, config): """Configure an object with a user-supplied factory.""" c = config.pop('()') if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: c = self.resolve(c) props = config.pop('.', None) # Check for valid identifiers kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) result = c(**kwargs) if props: for name, value in props.items(): setattr(result, name, value) return result
Configure an object with a user-supplied factory.
configure_custom
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def as_tuple(self, value): """Utility function which converts lists to tuples.""" if isinstance(value, list): value = tuple(value) return value
Utility function which converts lists to tuples.
as_tuple
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def common_logger_config(self, logger, config, incremental=False): """ Perform configuration which is common to root and non-root loggers. """ level = config.get('level', None) if level is not None: logger.setLevel(logging._checkLevel(level)) if not incremental: #Remove any existing handlers for h in logger.handlers[:]: logger.removeHandler(h) handlers = config.get('handlers', None) if handlers: self.add_handlers(logger, handlers) filters = config.get('filters', None) if filters: self.add_filters(logger, filters)
Perform configuration which is common to root and non-root loggers.
common_logger_config
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def configure_logger(self, name, config, incremental=False): """Configure a non-root logger from a dictionary.""" logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if propagate is not None: logger.propagate = propagate
Configure a non-root logger from a dictionary.
configure_logger
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def listen(port=DEFAULT_LOGGING_CONFIG_PORT): """ Start up a socket server on the specified port, and listen for new configurations. These will be sent as a file suitable for processing by fileConfig(). Returns a Thread object on which you can call start() to start the server, and which you can join() when appropriate. To stop the server, call stopListening(). """ if not thread: raise NotImplementedError("listen() needs threading to work") class ConfigStreamHandler(StreamRequestHandler): """ Handler for a logging configuration request. It expects a completely new logging configuration and uses fileConfig to install it. """ def handle(self): """ Handle a request. Each request is expected to be a 4-byte length, packed using struct.pack(">L", n), followed by the config file. Uses fileConfig() to do the grunt work. """ import tempfile try: conn = self.connection chunk = conn.recv(4) if len(chunk) == 4: slen = struct.unpack(">L", chunk)[0] chunk = self.connection.recv(slen) while len(chunk) < slen: chunk = chunk + conn.recv(slen - len(chunk)) try: import json d =json.loads(chunk) assert isinstance(d, dict) dictConfig(d) except: #Apply new configuration. file = cStringIO.StringIO(chunk) try: fileConfig(file) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() if self.server.ready: self.server.ready.set() except socket.error as e: if e.errno != RESET_ERROR: raise class ConfigSocketReceiver(ThreadingTCPServer): """ A simple TCP socket-based logging config receiver. """ allow_reuse_address = 1 def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT, handler=None, ready=None): ThreadingTCPServer.__init__(self, (host, port), handler) logging._acquireLock() self.abort = 0 logging._releaseLock() self.timeout = 1 self.ready = ready def serve_until_stopped(self): import select abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() logging._acquireLock() abort = self.abort logging._releaseLock() self.socket.close() class Server(threading.Thread): def __init__(self, rcvr, hdlr, port): super(Server, self).__init__() self.rcvr = rcvr self.hdlr = hdlr self.port = port self.ready = threading.Event() def run(self): server = self.rcvr(port=self.port, handler=self.hdlr, ready=self.ready) if self.port == 0: self.port = server.server_address[1] self.ready.set() global _listener logging._acquireLock() _listener = server logging._releaseLock() server.serve_until_stopped() return Server(ConfigSocketReceiver, ConfigStreamHandler, port)
Start up a socket server on the specified port, and listen for new configurations. These will be sent as a file suitable for processing by fileConfig(). Returns a Thread object on which you can call start() to start the server, and which you can join() when appropriate. To stop the server, call stopListening().
listen
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def handle(self): """ Handle a request. Each request is expected to be a 4-byte length, packed using struct.pack(">L", n), followed by the config file. Uses fileConfig() to do the grunt work. """ import tempfile try: conn = self.connection chunk = conn.recv(4) if len(chunk) == 4: slen = struct.unpack(">L", chunk)[0] chunk = self.connection.recv(slen) while len(chunk) < slen: chunk = chunk + conn.recv(slen - len(chunk)) try: import json d =json.loads(chunk) assert isinstance(d, dict) dictConfig(d) except: #Apply new configuration. file = cStringIO.StringIO(chunk) try: fileConfig(file) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() if self.server.ready: self.server.ready.set() except socket.error as e: if e.errno != RESET_ERROR: raise
Handle a request. Each request is expected to be a 4-byte length, packed using struct.pack(">L", n), followed by the config file. Uses fileConfig() to do the grunt work.
handle
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def stopListening(): """ Stop the listening server which was created with a call to listen(). """ global _listener logging._acquireLock() try: if _listener: _listener.abort = 1 _listener = None finally: logging._releaseLock()
Stop the listening server which was created with a call to listen().
stopListening
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/config.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/config.py
MIT
def __init__(self, filename, mode, encoding=None, delay=0): """ Use the specified filename for streamed logging """ if codecs is None: encoding = None logging.FileHandler.__init__(self, filename, mode, encoding, delay) self.mode = mode self.encoding = encoding
Use the specified filename for streamed logging
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0): """ Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. appended to it. For example, with a backupCount of 5 and a base file name of "app.log", you would get "app.log", "app.log.1", "app.log.2", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, it is closed and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. exist, then they are renamed to "app.log.2", "app.log.3" etc. respectively. If maxBytes is zero, rollover never occurs. """ # If rotation/rollover is wanted, it doesn't make sense to use another # mode. If for example 'w' were specified, then if there were multiple # runs of the calling application, the logs from previous runs would be # lost if the 'w' is respected, because the log file would be truncated # on each run. if maxBytes > 0: mode = 'a' BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) self.maxBytes = maxBytes self.backupCount = backupCount
Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. appended to it. For example, with a backupCount of 5 and a base file name of "app.log", you would get "app.log", "app.log.1", "app.log.2", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, it is closed and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. exist, then they are renamed to "app.log.2", "app.log.3" etc. respectively. If maxBytes is zero, rollover never occurs.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def computeRollover(self, currentTime): """ Work out the rollover time based on the specified time. """ result = currentTime + self.interval # If we are rolling over at midnight or weekly, then the interval is already known. # What we need to figure out is WHEN the next interval is. In other words, # if you are rolling over at midnight, then your base interval is 1 day, # but you want to start that one day clock at midnight, not now. So, we # have to fudge the rolloverAt value in order to trigger the first rollover # at the right time. After that, the regular interval will take care of # the rest. Note that this code doesn't care about leap seconds. :) if self.when == 'MIDNIGHT' or self.when.startswith('W'): # This could be done with less code, but I wanted it to be clear if self.utc: t = time.gmtime(currentTime) else: t = time.localtime(currentTime) currentHour = t[3] currentMinute = t[4] currentSecond = t[5] # r is the number of seconds left between now and midnight r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 + currentSecond) result = currentTime + r # If we are rolling over on a certain day, add in the number of days until # the next rollover, but offset by 1 since we just calculated the time # until the next day starts. There are three cases: # Case 1) The day to rollover is today; in this case, do nothing # Case 2) The day to rollover is further in the interval (i.e., today is # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to # next rollover is simply 6 - 2 - 1, or 3. # Case 3) The day to rollover is behind us in the interval (i.e., today # is day 5 (Saturday) and rollover is on day 3 (Thursday). # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the # number of days left in the current week (1) plus the number # of days in the next week until the rollover day (3). # The calculations described in 2) and 3) above need to have a day added. # This is because the above time calculation takes us to midnight on this # day, i.e. the start of the next day. if self.when.startswith('W'): day = t[6] # 0 is Monday if day != self.dayOfWeek: if day < self.dayOfWeek: daysToWait = self.dayOfWeek - day else: daysToWait = 6 - day + self.dayOfWeek + 1 newRolloverAt = result + (daysToWait * (60 * 60 * 24)) if not self.utc: dstNow = t[-1] dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend result = newRolloverAt return result
Work out the rollover time based on the specified time.
computeRollover
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def shouldRollover(self, record): """ Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so the method signatures are the same """ t = int(time.time()) if t >= self.rolloverAt: return 1 #print "No need to rollover: %d, %d" % (t, self.rolloverAt) return 0
Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so the method signatures are the same
shouldRollover
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def getFilesToDelete(self): """ Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). """ dirName, baseName = os.path.split(self.baseFilename) fileNames = os.listdir(dirName) result = [] prefix = baseName + "." plen = len(prefix) for fileName in fileNames: if fileName[:plen] == prefix: suffix = fileName[plen:] if self.extMatch.match(suffix): result.append(os.path.join(dirName, fileName)) result.sort() if len(result) < self.backupCount: result = [] else: result = result[:len(result) - self.backupCount] return result
Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob().
getFilesToDelete
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix. """ if self.stream: self.stream.close() self.stream = None # get the time that this sequence started at and make it a TimeTuple currentTime = int(time.time()) dstNow = time.localtime(currentTime)[-1] t = self.rolloverAt - self.interval if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) dstThen = timeTuple[-1] if dstNow != dstThen: if dstNow: addend = 3600 else: addend = -3600 timeTuple = time.localtime(t + addend) dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple) if os.path.exists(dfn): os.remove(dfn) # Issue 18940: A file may not have been created if delay is True. if os.path.exists(self.baseFilename): os.rename(self.baseFilename, dfn) if self.backupCount > 0: for s in self.getFilesToDelete(): os.remove(s) if not self.delay: self.stream = self._open() newRolloverAt = self.computeRollover(currentTime) while newRolloverAt <= currentTime: newRolloverAt = newRolloverAt + self.interval #If DST changes and midnight or weekly rollover, adjust for this. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend self.rolloverAt = newRolloverAt
do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix.
doRollover
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def __init__(self, host, port): """ Initializes the handler with a specific host address and port. The attribute 'closeOnError' is set to 1 - which means that if a socket error occurs, the socket is silently closed and then reopened on the next logging call. """ logging.Handler.__init__(self) self.host = host self.port = port self.sock = None self.closeOnError = 0 self.retryTime = None # # Exponential backoff parameters. # self.retryStart = 1.0 self.retryMax = 30.0 self.retryFactor = 2.0
Initializes the handler with a specific host address and port. The attribute 'closeOnError' is set to 1 - which means that if a socket error occurs, the socket is silently closed and then reopened on the next logging call.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def makeSocket(self, timeout=1): """ A factory method which allows subclasses to define the precise type of socket they want. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(s, 'settimeout'): s.settimeout(timeout) s.connect((self.host, self.port)) return s
A factory method which allows subclasses to define the precise type of socket they want.
makeSocket
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def createSocket(self): """ Try to create a socket, using an exponential backoff with a max retry time. Thanks to Robert Olson for the original patch (SF #815911) which has been slightly refactored. """ now = time.time() # Either retryTime is None, in which case this # is the first time back after a disconnect, or # we've waited long enough. if self.retryTime is None: attempt = 1 else: attempt = (now >= self.retryTime) if attempt: try: self.sock = self.makeSocket() self.retryTime = None # next time, no delay before trying except socket.error: #Creation failed, so set the retry time and return. if self.retryTime is None: self.retryPeriod = self.retryStart else: self.retryPeriod = self.retryPeriod * self.retryFactor if self.retryPeriod > self.retryMax: self.retryPeriod = self.retryMax self.retryTime = now + self.retryPeriod
Try to create a socket, using an exponential backoff with a max retry time. Thanks to Robert Olson for the original patch (SF #815911) which has been slightly refactored.
createSocket
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def send(self, s): """ Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy. """ if self.sock is None: self.createSocket() #self.sock can be None either because we haven't reached the retry #time yet, or because we have reached the retry time and retried, #but are still unable to connect. if self.sock: try: if hasattr(self.sock, "sendall"): self.sock.sendall(s) else: sentsofar = 0 left = len(s) while left > 0: sent = self.sock.send(s[sentsofar:]) sentsofar = sentsofar + sent left = left - sent except socket.error: self.sock.close() self.sock = None # so we can call createSocket next time
Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy.
send
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def makePickle(self, record): """ Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. """ ei = record.exc_info if ei: # just to get traceback text into record.exc_text ... dummy = self.format(record) record.exc_info = None # to avoid Unpickleable error # See issue #14436: If msg or args are objects, they may not be # available on the receiving end. So we convert the msg % args # to a string, save it as msg and zap the args. d = dict(record.__dict__) d['msg'] = record.getMessage() d['args'] = None s = cPickle.dumps(d, 1) if ei: record.exc_info = ei # for next handler slen = struct.pack(">L", len(s)) return slen + s
Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket.
makePickle
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def handleError(self, record): """ Handle an error during logging. An error has occurred during logging. Most likely cause - connection lost. Close the socket so that we can retry on the next event. """ if self.closeOnError and self.sock: self.sock.close() self.sock = None #try to reconnect next time else: logging.Handler.handleError(self, record)
Handle an error during logging. An error has occurred during logging. Most likely cause - connection lost. Close the socket so that we can retry on the next event.
handleError
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def __init__(self, host, port): """ Initializes the handler with a specific host address and port. """ SocketHandler.__init__(self, host, port) self.closeOnError = 0
Initializes the handler with a specific host address and port.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def send(self, s): """ Send a pickled string to a socket. This function no longer allows for partial sends which can happen when the network is busy - UDP does not guarantee delivery and can deliver packets out of sequence. """ if self.sock is None: self.createSocket() self.sock.sendto(s, (self.host, self.port))
Send a pickled string to a socket. This function no longer allows for partial sends which can happen when the network is busy - UDP does not guarantee delivery and can deliver packets out of sequence.
send
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=None): """ Initialize a handler. If address is specified as a string, a UNIX socket is used. To log to a local syslogd, "SysLogHandler(address="/dev/log")" can be used. If facility is not specified, LOG_USER is used. If socktype is specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific socket type will be used. For Unix sockets, you can also specify a socktype of None, in which case socket.SOCK_DGRAM will be used, falling back to socket.SOCK_STREAM. """ logging.Handler.__init__(self) self.address = address self.facility = facility self.socktype = socktype if isinstance(address, basestring): self.unixsocket = 1 self._connect_unixsocket(address) else: self.unixsocket = 0 if socktype is None: socktype = socket.SOCK_DGRAM self.socket = socket.socket(socket.AF_INET, socktype) if socktype == socket.SOCK_STREAM: self.socket.connect(address) self.socktype = socktype self.formatter = None
Initialize a handler. If address is specified as a string, a UNIX socket is used. To log to a local syslogd, "SysLogHandler(address="/dev/log")" can be used. If facility is not specified, LOG_USER is used. If socktype is specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific socket type will be used. For Unix sockets, you can also specify a socktype of None, in which case socket.SOCK_DGRAM will be used, falling back to socket.SOCK_STREAM.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def encodePriority(self, facility, priority): """ Encode the facility and priority. You can pass in strings or integers - if strings are passed, the facility_names and priority_names mapping dictionaries are used to convert them to integers. """ if isinstance(facility, basestring): facility = self.facility_names[facility] if isinstance(priority, basestring): priority = self.priority_names[priority] return (facility << 3) | priority
Encode the facility and priority. You can pass in strings or integers - if strings are passed, the facility_names and priority_names mapping dictionaries are used to convert them to integers.
encodePriority
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None): """ Initialize the handler. Initialize the instance with the from and to addresses and subject line of the email. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. To specify authentication credentials, supply a (username, password) tuple for the credentials argument. To specify the use of a secure protocol (TLS), pass in a tuple for the secure argument. This will only be used when authentication credentials are supplied. The tuple will be either an empty tuple, or a single-value tuple with the name of a keyfile, or a 2-value tuple with the names of the keyfile and certificate file. (This tuple is passed to the `starttls` method). """ logging.Handler.__init__(self) if isinstance(mailhost, (list, tuple)): self.mailhost, self.mailport = mailhost else: self.mailhost, self.mailport = mailhost, None if isinstance(credentials, (list, tuple)): self.username, self.password = credentials else: self.username = None self.fromaddr = fromaddr if isinstance(toaddrs, basestring): toaddrs = [toaddrs] self.toaddrs = toaddrs self.subject = subject self.secure = secure self._timeout = 5.0
Initialize the handler. Initialize the instance with the from and to addresses and subject line of the email. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. To specify authentication credentials, supply a (username, password) tuple for the credentials argument. To specify the use of a secure protocol (TLS), pass in a tuple for the secure argument. This will only be used when authentication credentials are supplied. The tuple will be either an empty tuple, or a single-value tuple with the name of a keyfile, or a 2-value tuple with the names of the keyfile and certificate file. (This tuple is passed to the `starttls` method).
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def __init__(self, host, url, method="GET"): """ Initialize the instance with the host, the request URL, and the method ("GET" or "POST") """ logging.Handler.__init__(self) method = method.upper() if method not in ["GET", "POST"]: raise ValueError("method must be GET or POST") self.host = host self.url = url self.method = method
Initialize the instance with the host, the request URL, and the method ("GET" or "POST")
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def __init__(self, capacity): """ Initialize the handler with the buffer size. """ logging.Handler.__init__(self) self.capacity = capacity self.buffer = []
Initialize the handler with the buffer size.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def flush(self): """ Override to implement custom flushing behaviour. This version just zaps the buffer to empty. """ self.acquire() try: self.buffer = [] finally: self.release()
Override to implement custom flushing behaviour. This version just zaps the buffer to empty.
flush
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def close(self): """ Close the handler. This version just flushes and chains to the parent class' close(). """ try: self.flush() finally: logging.Handler.close(self)
Close the handler. This version just flushes and chains to the parent class' close().
close
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def __init__(self, capacity, flushLevel=logging.ERROR, target=None): """ Initialize the handler with the buffer size, the level at which flushing should occur and an optional target. Note that without a target being set either here or via setTarget(), a MemoryHandler is no use to anyone! """ BufferingHandler.__init__(self, capacity) self.flushLevel = flushLevel self.target = target
Initialize the handler with the buffer size, the level at which flushing should occur and an optional target. Note that without a target being set either here or via setTarget(), a MemoryHandler is no use to anyone!
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def shouldFlush(self, record): """ Check for buffer full or a record at the flushLevel or higher. """ return (len(self.buffer) >= self.capacity) or \ (record.levelno >= self.flushLevel)
Check for buffer full or a record at the flushLevel or higher.
shouldFlush
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def flush(self): """ For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. Override if you want different behaviour. """ self.acquire() try: if self.target: for record in self.buffer: self.target.handle(record) self.buffer = [] finally: self.release()
For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. Override if you want different behaviour.
flush
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def close(self): """ Flush, set the target to None and lose the buffer. """ try: self.flush() finally: self.acquire() try: self.target = None BufferingHandler.close(self) finally: self.release()
Flush, set the target to None and lose the buffer.
close
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/handlers.py
MIT
def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except: return sys.exc_info()[2].tb_frame.f_back
Return the frame object for the caller's stack frame.
currentframe
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def addLevelName(level, levelName): """ Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting. """ _acquireLock() try: #unlikely to cause an exception, but you never know... _levelNames[level] = levelName _levelNames[levelName] = level finally: _releaseLock()
Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting.
addLevelName
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None): """ Initialize a logging record with interesting information. """ ct = time.time() self.name = name self.msg = msg # # The following statement allows passing of a dictionary as a sole # argument, so that you can do something like # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) # Suggested by Stefan Behnel. # Note that without the test for args[0], we get a problem because # during formatting, we test to see if the arg is present using # 'if self.args:'. If the event being logged is e.g. 'Value is %d' # and if the passed arg fails 'if self.args:' then no formatting # is done. For example, logger.warn('Value is %d', 0) would log # 'Value is %d' instead of 'Value is 0'. # For the use case of passing a dictionary, this should not be a # problem. # Issue #21172: a request was made to relax the isinstance check # to hasattr(args[0], '__getitem__'). However, the docs on string # formatting still seem to suggest a mapping object is required. # Thus, while not removing the isinstance check, it does now look # for collections.Mapping rather than, as before, dict. if (args and len(args) == 1 and isinstance(args[0], collections.Mapping) and args[0]): args = args[0] self.args = args self.levelname = getLevelName(level) self.levelno = level self.pathname = pathname try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info self.exc_text = None # used to cache the traceback text self.lineno = lineno self.funcName = func self.created = ct self.msecs = (ct - long(ct)) * 1000 self.relativeCreated = (self.created - _startTime) * 1000 if logThreads and thread: self.thread = thread.get_ident() self.threadName = threading.current_thread().name else: self.thread = None self.threadName = None if not logMultiprocessing: self.processName = None else: self.processName = 'MainProcess' mp = sys.modules.get('multiprocessing') if mp is not None: # Errors may occur if multiprocessing has not finished loading # yet - e.g. if a custom import hook causes third-party code # to run when multiprocessing calls import. See issue 8200 # for an example try: self.processName = mp.current_process().name except StandardError: pass if logProcesses and hasattr(os, 'getpid'): self.process = os.getpid() else: self.process = None
Initialize a logging record with interesting information.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ if not _unicode: #if no unicode support... msg = str(self.msg) else: msg = self.msg if not isinstance(msg, basestring): try: msg = str(self.msg) except UnicodeError: msg = self.msg #Defer encoding till later if self.args: msg = msg % self.args return msg
Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message.
getMessage
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def makeLogRecord(dict): """ Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance. """ rv = LogRecord(None, None, "", 0, "", (), None, None) rv.__dict__.update(dict) return rv
Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance.
makeLogRecord
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def formatTime(self, record, datefmt=None): """ Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class. """ ct = self.converter(record.created) if datefmt: s = time.strftime(datefmt, ct) else: t = time.strftime("%Y-%m-%d %H:%M:%S", ct) s = "%s,%03d" % (t, record.msecs) return s
Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class.
formatTime
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT
def formatException(self, ei): """ Format and return the specified exception information as a string. This default implementation just uses traceback.print_exception() """ sio = cStringIO.StringIO() traceback.print_exception(ei[0], ei[1], ei[2], None, sio) s = sio.getvalue() sio.close() if s[-1:] == "\n": s = s[:-1] return s
Format and return the specified exception information as a string. This default implementation just uses traceback.print_exception()
formatException
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/logging/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py
MIT