[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
Provenance
- Commit
b475cff- Tree
c14fb67- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d15a4dc
11 files changed+359 added−99 removed
modified:jinja/translators/python.py+3 added-16 removed
41 unmodified lines42 from jinja.parser import Parser43 from jinja.exceptions import TemplateSyntaxError44 from jinja.translators import Translator45 from jinja.datastructure import TemplateStream46-from jinja.utils import translate_exception, capture_generator, \46+from jinja.utils import set, translate_exception, capture_generator, \47 RUNTIME_EXCEPTION_OFFSET48 49 50 #: regular expression for the debug symbols51 _debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '52 r'lineno=(?P<lineno>\d+)\)$')53 54-# For Python2.3 compatibiilty54+# For Python versions without generator exit exceptions55 try:56- set56+ GeneratorExit = GeneratorExit57 except NameError:58- from sets import Set as set59-60-# For Python 2.3/2.4 compatibility61-try:62- GeneratorExit63-except NameError:58 class GeneratorExit(Exception):59 pass60 61 # For Pythons without conditional expressions355 unmodified lines417 418 # 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 lines456 str(name),457 self.to_tuple(tmp)458 ))459 467- # 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]472-460 # 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 linesmodified:jinja/_native.py+2 added-15 removed
11 unmodified lines12 13 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15 """16-from jinja.datastructure import Deferred, Undefined17-try:18- from collections import deque19-except ImportError:20- class deque(list):21- """22- Minimal subclass of list that provides the deque23- interface used by the native `BaseContext`.24- """16+from jinja.datastructure import Deferred17+from jinja.utils import deque18 26- def appendleft(self, item):27- list.insert(self, 0, item)19 29- def popleft(self):30- return list.pop(self, 0)31-32-20 class BaseContext(object):21 22 def __init__(self, undefined_singleton, globals, initial):23 self._undefined_singleton = undefined_singleton70 unmodified linesmodified:jinja/datastructure.py-6 removed
7 unmodified lines8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-# sets13-try:14- set15-except NameError:16- from sets import Set as set17-12 from jinja.exceptions import TemplateSyntaxError, TemplateRuntimeError13 14 15 def contextcallable(f):583 unmodified linesmodified:jinja/filters.py+3 added-18 removed
9 unmodified lines10 """11 import re12 from random import choice13 from urllib import urlencode, quote14-from jinja.utils import urlize, escape15-from jinja.datastructure import Markup, TemplateData14+from jinja.utils import urlize, escape, reversed15+from jinja.datastructure import TemplateData16 from jinja.exceptions import FilterArgumentError17 18 19-try:20- _reversed = reversed21-except 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')32-33-19 def stringfilter(f):20 """21 Decorator for filters that just work on unicode objects.22 """293 unmodified lines316 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 linesmodified:jinja/lexer.py+1 added-5 removed
23 unmodified lines24 """25 import re26 from jinja.datastructure import TokenStream27 from jinja.exceptions import TemplateSyntaxError28+from jinja.utils import set29 from weakref import WeakValueDictionary30 30-try:31- set32-except NameError:33- from sets import Set as set31 35-32 __all__ = ['Lexer', 'Failure', 'keywords']33 34 35 # cache for the lexers. Exists in order to be able to have multiple333 unmodified linesmodified:jinja/loaders.py+12 added-7 removed
16 unmodified lines17 from jinja.parser import Parser18 from jinja.translators.python import PythonTranslator, Template19 from jinja.exceptions import TemplateNotFound, TemplateSyntaxError20 from jinja.utils import CacheDict, raise_syntax_error21-try:22- from pkg_resources import resource_exists, resource_string, \23- resource_filename24-except ImportError:25- resource_exists = resource_string = resource_filename = None21 22 23 #: when updating this, update the listing in the jinja package too24 __all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',100 unmodified lines125 """126 ast = self.parse(environment, name, None)127 return translator.process(environment, ast)128 129+ def get_source(self, environment, name, parent):130+ """131+ Override this method to get the source for a template.132+ """133+ raise TemplateNotFound(name)134 135+136 class CachedLoaderMixin(object):137 """138 Mixin this class to implement simple memory and disk caching.139 """213 unmodified lines353 354 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)367 368 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)376 377 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 linesmodified:jinja/parser.py+2 added-7 removed
12 unmodified lines13 14 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16 """17-import re17 from compiler import ast, parse19-from compiler.misc import set_filename18 from jinja import nodes21-from jinja.datastructure import TokenStream, StateTest19+from jinja.datastructure import StateTest20 from jinja.exceptions import TemplateSyntaxError23-try:24- set25-except NameError:26- from sets import Set as set21+from jinja.utils import set22 23 24 __all__ = ['Parser']25 799 unmodified linesmodified:jinja/tests.py-1 removed
10 unmodified lines11 import re12 13 14 number_re = re.compile(r'^-?\d+(\.\d+)?$')15-15 regex_type = type(number_re)16 17 18 def test_odd():105 unmodified linesmodified:jinja/utils.py+32 added-24 removed
15 unmodified lines16 import string17 from types import MethodType, FunctionType18 from compiler.ast import CallFunc, Name, Const19 from jinja.nodes import Trans20-from jinja.datastructure import Context20 from jinja.exceptions import SecurityException, TemplateNotFound21 22 # the python2.4 version of deque is missing the remove method23 # because a for loop with a lookup for the missing value written1 unmodified line25 try:26 from collections import deque27 deque.remove28 except (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[:]41 42+# support for a working reversed()43+try:44+ reversed = reversed45+except 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])53+54 # support for python 2.3/2.455 try:34- set56+ set = set57 except NameError:58 from sets import Set as set59 60 #: number of maximal range items236 unmodified lines297 """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))302 303 304 def empty_block(context):305 """10 unmodified lines316 object. This is used for runtime debugging, not compile time.317 """318 # some traceback systems allow to skip frames319 __traceback_hide__ = True320+321+ 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 lines562 563 def __init__(self, capacity):564 self.capacity = capacity565 self._mapping = {}566+ self._queue = deque()567 545- # 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)554-568 # 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 lines602 """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[:]607 608 def __contains__(self, key):609 """610 Check if a key exists in this cache dict.49 unmodified lines660 """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])665 666 def __reversed__(self):667 """668 Iterate over the values in the cache dict, oldest items15 unmodified linesadded: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]10+11+# Specify a configuration file.12+#rcfile=13+14+# Profiled execution.15+profile=no16+17+# Add <file or directory> to the black list. It should be a base name, not a18+# path. You may set this option multiple times.19+ignore=.svn20+21+# Pickle collected data for later comparisons.22+persistent=yes23+24+# Set the cache size for astng objects.25+cache-size=50026+27+# List of plugins (as comma separated values of python modules names) to load,28+# usually to register additional checkers.29+load-plugins=30+31+32+[MESSAGES CONTROL]33+34+# Enable only checker(s) with the given id(s). This option conflict with the35+# disable-checker option36+#enable-checker=37+38+# Enable all checker(s) except those with the given id(s). This option conflict39+# with the disable-checker option40+#disable-checker=41+42+# Enable all messages in the listed categories.43+#enable-msg-cat=44+45+# Disable all messages in the listed categories.46+#disable-msg-cat=47+48+# Enable the message(s) with the given id(s).49+#enable-msg=50+51+# Disable the message(s) with the given id(s).52+disable-msg=C0323,W0142,C0301,C0103,C0111,E0213,C0302,C0203,W0703,R020153+54+55+[REPORTS]56+57+# set the output format. Available formats are text, parseable, colorized and58+# html59+output-format=colorized60+61+# Include message's id in output62+include-ids=yes63+64+# 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]".67+files-output=no68+69+# Tells wether to display a full report or only the messages70+reports=yes71+72+# 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).77+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)78+79+# Add a comment according to your evaluation note. This is used by the global80+# evaluation report (R0004).81+comment=no82+83+# Enable the report(s) with the given id(s).84+#enable-report=85+86+# Disable the report(s) with the given id(s).87+#disable-report=88+89+90+# checks for91+# * unused variables / imports92+# * undefined variables93+# * redefinition of variable from builtins or from an outer scope94+# * use of variable before assigment95+# 96+[VARIABLES]97+98+# Tells wether we should check for unused import in __init__ files.99+init-import=no100+101+# A regular expression matching names used for dummy variables (i.e. not used).102+dummy-variables-rgx=_|dummy103+104+# List of additional names supposed to be defined in builtins. Remember that105+# you should avoid to define new builtins when possible.106+additional-builtins=107+108+109+# try to find bugs in the code using type inference110+# 111+[TYPECHECK]112+113+# Tells wether missing members accessed in mixin class should be ignored. A114+# mixin class is detected if its name ends with "mixin" (case insensitive).115+ignore-mixin-members=yes116+117+# When zope mode is activated, consider the acquired-members option to ignore118+# access to some undefined attributes.119+zope=no120+121+# 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).123+acquired-members=REQUEST,acl_users,aq_parent124+125+126+# 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]137+138+# Required attributes for module, separated by a comma139+required-attributes=140+141+# Regular expression which should only match functions or classes name which do142+# not require a docstring143+no-docstring-rgx=__.*__144+145+# Regular expression which should only match correct module names146+module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$147+148+# Regular expression which should only match correct module level names149+const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$150+151+# Regular expression which should only match correct class names152+class-rgx=[A-Z_][a-zA-Z0-9]+$153+154+# Regular expression which should only match correct function names155+function-rgx=[a-z_][a-z0-9_]*$156+157+# Regular expression which should only match correct method names158+method-rgx=[a-z_][a-z0-9_]*$159+160+# Regular expression which should only match correct instance attribute names161+attr-rgx=[a-z_][a-z0-9_]*$162+163+# Regular expression which should only match correct argument names164+argument-rgx=[a-z_][a-z0-9_]*$165+166+# Regular expression which should only match correct variable names167+variable-rgx=[a-z_][a-z0-9_]*$168+169+# Regular expression which should only match correct list comprehension /170+# generator expression variable names171+inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$172+173+# Good variable names which should always be accepted, separated by a comma174+good-names=i,j,k,ex,Run,_175+176+# Bad variable names which should always be refused, separated by a comma177+bad-names=foo,bar,baz,toto,tutu,tata178+179+# List of builtins function names that should not be used, separated by a comma180+bad-functions=apply,input181+182+183+# checks for sign of poor/misdesign:184+# * number of methods, attributes, local variables...185+# * size, complexity of functions, methods186+# 187+[DESIGN]188+189+# Maximum number of arguments for function / method190+max-args=12191+192+# Maximum number of locals for function / method body193+max-locals=30194+195+# Maximum number of return / yield for function / method body196+max-returns=12197+198+# Maximum number of branch for function / method body199+max-branchs=30200+201+# Maximum number of statements in function / method body202+max-statements=60203+204+# Maximum number of parents for a class (see R0901).205+max-parents=7206+207+# Maximum number of attributes for a class (see R0902).208+max-attributes=20209+210+# Minimum number of public methods for a class (see R0903).211+min-public-methods=0212+213+# Maximum number of public methods for a class (see R0904).214+max-public-methods=20215+216+217+# checks for218+# * external modules dependencies219+# * relative / wildcard imports220+# * cyclic imports221+# * uses of deprecated modules222+# 223+[IMPORTS]224+225+# Deprecated modules which should not be used, separated by a comma226+deprecated-modules=regsub,string,TERMIOS,Bastion,rexec227+228+# Create a graph of every (i.e. internal and external) dependencies in the229+# given file (report R0402 must not be disabled)230+import-graph=231+232+# Create a graph of external dependencies in the given file (report R0402 must233+# not be disabled)234+ext-import-graph=235+236+# Create a graph of internal dependencies in the given file (report R0402 must237+# not be disabled)238+int-import-graph=239+240+241+# 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]250+251+# 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.253+ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by254+255+# List of method names used to declare (i.e. assign) instance attributes.256+defining-attr-methods=__init__,__new__,setUp257+258+259+# 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]264+265+# Minimum lines number of a similarity.266+min-similarity-lines=10267+268+# Ignore comments when computing similarities.269+ignore-comments=yes270+271+# Ignore docstrings when computing similarities.272+ignore-docstrings=yes273+274+275+# 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]280+281+# List of note tags to take in consideration, separated by a comma.282+notes=FIXME,XXX,TODO283+284+285+# checks for :286+# * unauthorized constructions287+# * strict indentation288+# * line length289+# * use of <> instead of !=290+# 291+[FORMAT]292+293+# Maximum number of characters on a single line.294+max-line-length=90295+296+# Maximum number of lines in a module297+max-module-lines=1000298+299+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1300+# tab).301+indent-string=' 'modified:Makefile+3 added
18 unmodified lines19 20 webpage:21 @(cd ../www; ./generate.py)22 23+pylint:24+ @pylint --rcfile scripts/pylintrc jinja25+26 release: 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)