Skip to content
Myr

[svn] added pylint script for jinja and cleaned code up a bit (and importing is faster now)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent d15a4dc · Browse files · 11 files+359 added−99 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+359 added−99 removed

  • other:+359 added−99 removed

11 files+359 added−99 removed

modified:jinja/translators/python.py+3 added-16 removed
41 unmodified lines
42from jinja.parser import Parser43from jinja.exceptions import TemplateSyntaxError44from jinja.translators import Translator45from jinja.datastructure import TemplateStream46from jinja.utils import translate_exception, capture_generator, \46from jinja.utils import set, translate_exception, capture_generator, \47 RUNTIME_EXCEPTION_OFFSET484950#: regular expression for the debug symbols51_debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '52 r'lineno=(?P<lineno>\d+)\)$')5354# For Python2.3 compatibiilty54# For Python versions without generator exit exceptions55try:56 set56 GeneratorExit = GeneratorExit57except NameError:58 from sets import Set as set5960# For Python 2.3/2.4 compatibility61try:62 GeneratorExit63except NameError:58 class GeneratorExit(Exception):59 pass6061# For Pythons without conditional expressions
355 unmodified lines
417418 # handle requirements code419 if requirements:420 requirement_lines = ['def bootstrap(context):']427 has_requirements = False421 for n in requirements:422 requirement_lines.append(self.handle_node(n))423 requirement_lines.append(' if 0: yield None\n')424
31 unmodified lines
456 str(name),457 self.to_tuple(tmp)458 ))459467 # aliases boilerplate468 aliases = ['%s = environment.%s' % (item, item) for item in469 ['get_attribute', 'perform_test', 'apply_filters',470 'call_function', 'call_function_simple', 'finish_var',471 'undefined_singleton'] if item in self.used_shortcuts]472460 # bootstrapping code461 lines = ['# Essential imports', 'from __future__ import division']462 if self.used_utils:463 lines.append('from jinja.utils import %s' % ', '.join(self.used_utils))
752 unmodified lines
modified:jinja/_native.py+2 added-15 removed
11 unmodified lines
1213 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16from jinja.datastructure import Deferred, Undefined17try:18 from collections import deque19except ImportError:20 class deque(list):21 """22 Minimal subclass of list that provides the deque23 interface used by the native `BaseContext`.24 """16from jinja.datastructure import Deferred17from jinja.utils import deque1826 def appendleft(self, item):27 list.insert(self, 0, item)1929 def popleft(self):30 return list.pop(self, 0)313220class BaseContext(object):2122 def __init__(self, undefined_singleton, globals, initial):23 self._undefined_singleton = undefined_singleton
70 unmodified lines
modified:jinja/datastructure.py-6 removed
7 unmodified lines
8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112# sets13try:14 set15except NameError:16 from sets import Set as set1712from jinja.exceptions import TemplateSyntaxError, TemplateRuntimeError131415def contextcallable(f):
583 unmodified lines
modified:jinja/filters.py+3 added-18 removed
9 unmodified lines
10"""11import re12from random import choice13from urllib import urlencode, quote14from jinja.utils import urlize, escape15from jinja.datastructure import Markup, TemplateData14from jinja.utils import urlize, escape, reversed15from jinja.datastructure import TemplateData16from jinja.exceptions import FilterArgumentError171819try:20 _reversed = reversed21except NameError:22 # python2.3 compatibility hack for the do_reverse function23 def _reversed(seq):24 try:25 return seq[::-1]26 except:27 try:28 return list(seq)[::-1]29 except:30 raise TypeError('argument to _reversed must '31 'be a sequence')323319def stringfilter(f):20 """21 Decorator for filters that just work on unicode objects.22 """
293 unmodified lines
316 Return the last item of a sequence.317 """318 def wrapped(env, context, seq):319 try:335 return iter(_reversed(seq)).next()320 return iter(reversed(seq)).next()321 except StopIteration:322 return env.undefined_singleton323 return wrapped324
543 unmodified lines
modified:jinja/lexer.py+1 added-5 removed
23 unmodified lines
24"""25import re26from jinja.datastructure import TokenStream27from jinja.exceptions import TemplateSyntaxError28from jinja.utils import set29from weakref import WeakValueDictionary3030try:31 set32except NameError:33 from sets import Set as set313532__all__ = ['Lexer', 'Failure', 'keywords']333435# cache for the lexers. Exists in order to be able to have multiple
333 unmodified lines
modified:jinja/loaders.py+12 added-7 removed
16 unmodified lines
17from jinja.parser import Parser18from jinja.translators.python import PythonTranslator, Template19from jinja.exceptions import TemplateNotFound, TemplateSyntaxError20from jinja.utils import CacheDict, raise_syntax_error21try:22 from pkg_resources import resource_exists, resource_string, \23 resource_filename24except ImportError:25 resource_exists = resource_string = resource_filename = None212223#: when updating this, update the listing in the jinja package too24__all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',
100 unmodified lines
125 """126 ast = self.parse(environment, name, None)127 return translator.process(environment, ast)128129 def get_source(self, environment, name, parent):130 """131 Override this method to get the source for a template.132 """133 raise TemplateNotFound(name)134135136class CachedLoaderMixin(object):137 """138 Mixin this class to implement simple memory and disk caching.139 """
213 unmodified lines
353354 def __init__(self, package_name, package_path, use_memcache=False,355 memcache_size=40, cache_folder=None, auto_reload=True,356 cache_salt=None):356 if resource_filename is None:357 raise ImportError('setuptools not found')357 try:358 import pkg_resources359 except ImportError:360 raise RuntimeError('setuptools not installed')361 self.package_name = package_name362 self.package_path = package_path363 if cache_salt is None:364 cache_salt = package_name + '/' + package_path365 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,366 cache_folder, auto_reload, cache_salt)367368 def get_source(self, environment, name, parent):369 from pkg_resources import resource_exists, resource_string370 name = '/'.join([self.package_path] + [p for p in name.split('/')371 if p != '..'])372 if not resource_exists(self.package_name, name):373 raise TemplateNotFound(name)374 contents = resource_string(self.package_name, name)375 return contents.decode(environment.template_charset)376377 def check_source_changed(self, environment, name):378 from pkg_resources import resource_exists, resource_filename379 fn = resource_filename(self.package_name, '/'.join([self.package_path] +380 [p for p in name.split('/') if p and p[0] != '.']))381 if resource_exists(self.package_name, fn):382 return path.getmtime(fn)
141 unmodified lines
modified:jinja/parser.py+2 added-7 removed
12 unmodified lines
1314 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16"""17import re17from compiler import ast, parse19from compiler.misc import set_filename18from jinja import nodes21from jinja.datastructure import TokenStream, StateTest19from jinja.datastructure import StateTest20from jinja.exceptions import TemplateSyntaxError23try:24 set25except NameError:26 from sets import Set as set21from jinja.utils import set222324__all__ = ['Parser']25
799 unmodified lines
modified:jinja/tests.py-1 removed
10 unmodified lines
11import re121314number_re = re.compile(r'^-?\d+(\.\d+)?$')1515regex_type = type(number_re)161718def test_odd():
105 unmodified lines
modified:jinja/utils.py+32 added-24 removed
15 unmodified lines
16import string17from types import MethodType, FunctionType18from compiler.ast import CallFunc, Name, Const19from jinja.nodes import Trans20from jinja.datastructure import Context20from jinja.exceptions import SecurityException, TemplateNotFound2122# the python2.4 version of deque is missing the remove method23# because a for loop with a lookup for the missing value written
1 unmodified line
25try:26 from collections import deque27 deque.remove28except (ImportError, AttributeError):30 deque = None29 class deque(list):30 """31 Minimal subclass of list that provides the deque32 interface used by the native `BaseContext` and the33 `CacheDict`34 """35 def appendleft(self, item):36 list.insert(self, 0, item)37 def popleft(self):38 return list.pop(self, 0)39 def clear(self):40 del self[:]4142# support for a working reversed()43try:44 reversed = reversed45except NameError:46 def reversed(iterable):47 if hasattr(iterable, '__reversed__'):48 return iterable.__reversed__()49 try:50 return iter(iterable[::-1])51 except TypeError:52 return iter(tuple(iterable)[::-1])5354# support for python 2.3/2.455try:34 set56 set = set57except NameError:58 from sets import Set as set5960#: number of maximal range items
236 unmodified lines
297 """298 Used by the python translator to capture output of substreams.299 (macros, filter sections etc)300 """279 def wrapped(*args, **kwargs):280 return capture_generator(f(*args, **kwargs))281 return wrapped301 return lambda *a, **kw: capture_generator(f(*a, **kw))302303304def empty_block(context):305 """
10 unmodified lines
316 object. This is used for runtime debugging, not compile time.317 """318 # some traceback systems allow to skip frames319 __traceback_hide__ = True320321 from jinja.datastructure import Context322 if isinstance(context_or_env, Context):323 env = context_or_env.environment324 namespace = context_or_env.to_dict()325 else:
236 unmodified lines
562563 def __init__(self, capacity):564 self.capacity = capacity565 self._mapping = {}566 self._queue = deque()567545 # use a deque here if possible546 if deque is not None:547 self._queue = deque()548 self._popleft = self._queue.popleft549 # python2.3/2.4, just use a list550 else:551 self._queue = []552 pop = self._queue.pop553 self._popleft = lambda: pop(0)554568 # alias all queue methods for faster lookup569 self._popleft = self._queue.popleft570 self._pop = self._queue.pop571 self._remove = self._queue.remove572 self._append = self._queue.append573
28 unmodified lines
602 """603 Clear the cache dict.604 """605 self._mapping.clear()592 try:593 self._queue.clear()606 self._queue.clear()594 except AttributeError:595 del self._queue[:]607608 def __contains__(self, key):609 """610 Check if a key exists in this cache dict.
49 unmodified lines
660 """661 Iterate over all values in the cache dict, ordered by662 the most recent usage.663 """653 try:654 return reversed(self._queue)664 return reversed(self._queue)655 except NameError:656 return iter(self._queue[::-1])665666 def __reversed__(self):667 """668 Iterate over the values in the cache dict, oldest items
15 unmodified lines
added:scripts/pylintrc+301 added
1# lint Python modules using external checkers.2# 3# This is the main checker controling the other ones and the reports4# generation. It is itself both a raw checker and an astng checker in order5# to:6# * handle message activation / deactivation at the module level7# * handle some basic but necessary stats'data (number of classes, methods...)8# 9[MASTER]1011# Specify a configuration file.12#rcfile=1314# Profiled execution.15profile=no1617# Add <file or directory> to the black list. It should be a base name, not a18# path. You may set this option multiple times.19ignore=.svn2021# Pickle collected data for later comparisons.22persistent=yes2324# Set the cache size for astng objects.25cache-size=5002627# List of plugins (as comma separated values of python modules names) to load,28# usually to register additional checkers.29load-plugins=303132[MESSAGES CONTROL]3334# Enable only checker(s) with the given id(s). This option conflict with the35# disable-checker option36#enable-checker=3738# Enable all checker(s) except those with the given id(s). This option conflict39# with the disable-checker option40#disable-checker=4142# Enable all messages in the listed categories.43#enable-msg-cat=4445# Disable all messages in the listed categories.46#disable-msg-cat=4748# Enable the message(s) with the given id(s).49#enable-msg=5051# Disable the message(s) with the given id(s).52disable-msg=C0323,W0142,C0301,C0103,C0111,E0213,C0302,C0203,W0703,R0201535455[REPORTS]5657# set the output format. Available formats are text, parseable, colorized and58# html59output-format=colorized6061# Include message's id in output62include-ids=yes6364# Put messages in a separate file for each module / package specified on the65# command line instead of printing them on stdout. Reports (if any) will be66# written in a file name "pylint_global.[txt|html]".67files-output=no6869# Tells wether to display a full report or only the messages70reports=yes7172# Python expression which should return a note less than 10 (10 is the highest73# note).You have access to the variables errors warning, statement which74# respectivly contain the number of errors / warnings messages and the total75# number of statements analyzed. This is used by the global evaluation report76# (R0004).77evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)7879# Add a comment according to your evaluation note. This is used by the global80# evaluation report (R0004).81comment=no8283# Enable the report(s) with the given id(s).84#enable-report=8586# Disable the report(s) with the given id(s).87#disable-report=888990# checks for91# * unused variables / imports92# * undefined variables93# * redefinition of variable from builtins or from an outer scope94# * use of variable before assigment95# 96[VARIABLES]9798# Tells wether we should check for unused import in __init__ files.99init-import=no100101# A regular expression matching names used for dummy variables (i.e. not used).102dummy-variables-rgx=_|dummy103104# List of additional names supposed to be defined in builtins. Remember that105# you should avoid to define new builtins when possible.106additional-builtins=107108109# try to find bugs in the code using type inference110# 111[TYPECHECK]112113# Tells wether missing members accessed in mixin class should be ignored. A114# mixin class is detected if its name ends with "mixin" (case insensitive).115ignore-mixin-members=yes116117# When zope mode is activated, consider the acquired-members option to ignore118# access to some undefined attributes.119zope=no120121# List of members which are usually get through zope's acquisition mecanism and122# so shouldn't trigger E0201 when accessed (need zope=yes to be considered).123acquired-members=REQUEST,acl_users,aq_parent124125126# checks for :127# * doc strings128# * modules / classes / functions / methods / arguments / variables name129# * number of arguments, local variables, branchs, returns and statements in130# functions, methods131# * required module attributes132# * dangerous default values as arguments133# * redefinition of function / method / class134# * uses of the global statement135# 136[BASIC]137138# Required attributes for module, separated by a comma139required-attributes=140141# Regular expression which should only match functions or classes name which do142# not require a docstring143no-docstring-rgx=__.*__144145# Regular expression which should only match correct module names146module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$147148# Regular expression which should only match correct module level names149const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$150151# Regular expression which should only match correct class names152class-rgx=[A-Z_][a-zA-Z0-9]+$153154# Regular expression which should only match correct function names155function-rgx=[a-z_][a-z0-9_]*$156157# Regular expression which should only match correct method names158method-rgx=[a-z_][a-z0-9_]*$159160# Regular expression which should only match correct instance attribute names161attr-rgx=[a-z_][a-z0-9_]*$162163# Regular expression which should only match correct argument names164argument-rgx=[a-z_][a-z0-9_]*$165166# Regular expression which should only match correct variable names167variable-rgx=[a-z_][a-z0-9_]*$168169# Regular expression which should only match correct list comprehension /170# generator expression variable names171inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$172173# Good variable names which should always be accepted, separated by a comma174good-names=i,j,k,ex,Run,_175176# Bad variable names which should always be refused, separated by a comma177bad-names=foo,bar,baz,toto,tutu,tata178179# List of builtins function names that should not be used, separated by a comma180bad-functions=apply,input181182183# checks for sign of poor/misdesign:184# * number of methods, attributes, local variables...185# * size, complexity of functions, methods186# 187[DESIGN]188189# Maximum number of arguments for function / method190max-args=12191192# Maximum number of locals for function / method body193max-locals=30194195# Maximum number of return / yield for function / method body196max-returns=12197198# Maximum number of branch for function / method body199max-branchs=30200201# Maximum number of statements in function / method body202max-statements=60203204# Maximum number of parents for a class (see R0901).205max-parents=7206207# Maximum number of attributes for a class (see R0902).208max-attributes=20209210# Minimum number of public methods for a class (see R0903).211min-public-methods=0212213# Maximum number of public methods for a class (see R0904).214max-public-methods=20215216217# checks for218# * external modules dependencies219# * relative / wildcard imports220# * cyclic imports221# * uses of deprecated modules222# 223[IMPORTS]224225# Deprecated modules which should not be used, separated by a comma226deprecated-modules=regsub,string,TERMIOS,Bastion,rexec227228# Create a graph of every (i.e. internal and external) dependencies in the229# given file (report R0402 must not be disabled)230import-graph=231232# Create a graph of external dependencies in the given file (report R0402 must233# not be disabled)234ext-import-graph=235236# Create a graph of internal dependencies in the given file (report R0402 must237# not be disabled)238int-import-graph=239240241# checks for :242# * methods without self as first argument243# * overridden methods signature244# * access only to existant members via self245# * attributes not defined in the __init__ method246# * supported interfaces implementation247# * unreachable code248# 249[CLASSES]250251# List of interface methods to ignore, separated by a comma. This is used for252# instance to not check methods defines in Zope's Interface base class.253ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by254255# List of method names used to declare (i.e. assign) instance attributes.256defining-attr-methods=__init__,__new__,setUp257258259# checks for similarities and duplicated code. This computation may be260# memory / CPU intensive, so you should disable it if you experiments some261# problems.262# 263[SIMILARITIES]264265# Minimum lines number of a similarity.266min-similarity-lines=10267268# Ignore comments when computing similarities.269ignore-comments=yes270271# Ignore docstrings when computing similarities.272ignore-docstrings=yes273274275# checks for:276# * warning notes in the code like FIXME, XXX277# * PEP 263: source code with non ascii character but no encoding declaration278# 279[MISCELLANEOUS]280281# List of note tags to take in consideration, separated by a comma.282notes=FIXME,XXX,TODO283284285# checks for :286# * unauthorized constructions287# * strict indentation288# * line length289# * use of <> instead of !=290# 291[FORMAT]292293# Maximum number of characters on a single line.294max-line-length=90295296# Maximum number of lines in a module297max-module-lines=1000298299# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1300# tab).301indent-string=' '
modified:Makefile+3 added
18 unmodified lines
1920webpage:21 @(cd ../www; ./generate.py)2223pylint:24 @pylint --rcfile scripts/pylintrc jinja2526release: documentation27 @(python2.3 setup.py release bdist_egg upload; python2.4 setup.py release bdist_egg upload; python2.5 setup.py release bdist_egg sdist upload)