o ˝`z}@sjUdZddlZddlZddlZddlZddlmZddlm Z ddlm Z ddl m Z ddl mZdd l mZdd lmZdd lmZdd lmZdd lmZddlmZejrddlZddlmZddlmZddlmZGdddejZ Gddde Z!ej"e e!fZ#dZ$ej%e&dfe'd<e(dZ)GdddZ*ededej+dej+dej"ej+effd d!Z,d"ej-e&ge&fdej-de&ffd#d$Z.d"ej-e&e&e/ge&fdej-de&ffd%d&Z0d"ej-e&e&ge&fdej-de&ffd'd(Z1d"ej-e&e&e&e/ge&fdej-de&ffd)d*Z2Gd+d,d,e*Z3Gd-d.d.e*Z4Gd/d0d0e*Z5Gd1d2d2e*Z6Gd3d4d4e*Z7Gd5d6d6e*Z8e$d7fd8e j9d9ej:e&d:e;dejGd=d>d>Z?d?ej@d@ej:e&dAej:e&dBejAe&ej+fdejr?r@rrr preprocesscszExtension.preprocessstreamrrcCrA)a It's passed a :class:`~jinja2.lexer.TokenStream` that can be used to filter tokens returned. This method has to return an iterable of :class:`~jinja2.lexer.Token`\s, but it doesn't have to return a :class:`~jinja2.lexer.TokenStream`. r)rrCrrr filter_streamlszExtension.filter_streamparserrcCst)aIf any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes. )NotImplementedError)rrErrrparsevszExtension.parselinenocCstj|j||dS)zReturn an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) rH)rExtensionAttributer+)rr?rHrrrattr~s zExtension.attrargskwargsdyn_args dyn_kwargscCs8|durg}|dur g}tj|j||d|||||dS)zsCall a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`. NrI)rCallrK)rr?rLrMrNrOrHrrr call_methods  zExtension.call_method)rNr)NNNNN) rr r!__doc__r5ClassVarr"__annotations__r.setr0Setpriorityrr4r=OptionalrBUnionIterablerDrNodeListrGr#rJrKExprKeywordrPrQrrrrr*7sh     &     r* __contextrLrMrcOs|j|dg|Ri|S)Nr)callresolve)r_rLrMrrr_gettext_aliassrbfuncc s(tdtdtdtjdtffdd }|S)Nr___string variablesrcs$||}|jjrt|}||Sr)r`eval_ctx autoescaper)r_rdrer<rcrrrs z"_make_new_gettext..gettextr r r"r5Any)rcrrrhr_make_new_gettexts" rkc s0tdtdtdtdtdtjdtf fdd }|S) Nr_ __singular__plural__numrercs4|d|||||}|jjrt|}||S)Nnum setdefaultr`rfrgr)r_rlrmrnrer<rhrrrs z$_make_new_ngettext..ngettextr r r"r#r5rj)rcrrrhr_make_new_ngettextsrsc s,tdtdtdtdtjdtf fdd }|S)Nr_ __string_ctxrdrercs2|d||||}|jjrt|}||S)Nr%rp)r_rtrdrer<rhrrr&s z$_make_new_pgettext..pgettextri)rcr&rrhr_make_new_pgettexts rucs4tdtdtdtdtdtdtjdtffdd }|S) Nr_rtrlrmrnrercsB|d||d||||||}|jjrt|}||S)Nr%rorp)r_rtrlrmrnrer<rhrrr's z&_make_new_npgettext..npgettextrr)rcr'rrhr_make_new_npgettexts"rvcseZdZdZdhZdeddffdd Z d/dd d eje ddfd d Z d/d eje ddfd dZ   d0dej e ge fdej e e ege fd eje dejej e e ge fdejej e e e ege fddf ddZd1ddZefdeje ejfdeje dejejee ejeje ejeje dffffddZdddejejejejffddZefd e d!eje de fd"d#Zddd$e dejeje e ffd%d&Zd'e d(eje d)ej e ej!fd*ejej!d+e d,e dej"fd-d.Z#Z$S)2InternationalizationExtensionz-This extension adds gettext support to Jinja.transr2rNcs:t|t|jd<|j|j|j|j|j|j dddS)Nr(F)install_gettext_translationsinstall_null_translationsinstall_gettext_callablesuninstall_gettext_translationsextract_translationsnewstyle_gettext) superr4rbglobalsextend_install _install_null_install_callables _uninstall_extractr3r9rrr4s   z&InternationalizationExtension.__init__ translations_SupportedTranslationsnewstylecCsdt|dd}|dur |j}t|dd}|dur|j}t|dd}t|dd}|j|||||ddS)Nugettext ungettextr&r')rr&r')getattrrrr)rrrrrr&r'rrrrs      z&InternationalizationExtension._installc Csddl}|}t|dr|j}n dtdtdtfdd}t|dr%|j}ndtdtd td tdtf d d }|j|j|j|||d dS)Nrr&csrcSrArr)rrrrrr&*rz=InternationalizationExtension._install_null..pgettextr'prcSs|dkr|S|S)Nrr)rrrrrrrr'1z>InternationalizationExtension._install_null..npgettext)rrrr&r') rNullTranslationshasattrr&r"r'r#rr)rrrrr&r'rrrr s   z+InternationalizationExtension._install_nullrrr&r'cCsb|dur||j_|jjr$t|}t|}|durt|}|dur$t|}|jjj||||ddSN)rrr&r')r2r~rkrsrurvrr;)rrrrr&r'rrrr<s z0InternationalizationExtension._install_callablescCsdD] }|jj|dqdSr)r2rpop)rrkeyrrrrTsz(InternationalizationExtension._uninstallr>gettext_functions.cCs t|tr |j|}t||Sr) isinstancer"r2rGextract_from_ast)rr>rrrrrXs   z&InternationalizationExtension._extractrErcCst|jj}d}d}d}i}d}|jjjdkr|r|jd|jdr&nx|jd}|j|vr?|jd|jd|jt d |jjjd krUt|j| ||j<} n|durd|jd vrd|jd k}qt |jd ||j<} |durt | t jrt dd }|||j<t t dd| }n| }|jdk}|jjjdks|jdd} d} t} ||d\} }| r| | |durt | dd }| ddk}|jjdrd} t|j|jjjdkr|jd}|j|vr|jd|jd|jt d ||j}|jdk}|jd||d\}} t|j| |nt|j| D]}||vr5t |d ||<q&| s=d}n |durH|d||durS|jjd}|rc||}| rc|| } ||| ||t| |op| }|||dur||gS|S)zParse a translatable tag.FN block_endcommacolonr?ztranslatable variable z defined twice.)excassign)trimmed notrimmedrload_transstoreroTrname:pluralizezunknown variable z for pluralizationzpluralize without variablesext.i18n.trimmed)nextrCrHcurrenttypeexpectskip_ifvaluefailrparse_expressionrNamerrPAssignrU _parse_blockr;testr2policies_trim_whitespace _make_nodebool set_lineno)rrErHnum_called_num plural_exprplural_expr_assignmentrertokenvarr have_plural referencedsingular_namesr plural_namesr?noderrrrGcs              %                     z#InternationalizationExtension.parsestring_ws_recCs|d|S)N )substrip)rrrrrrrrz.InternationalizationExtension._trim_whitespaceallow_pluralizecCsg}g} |jjjdkr||jjjddt|jn_|jjjdkrFt|j|jdj}|||d|d|jd n7|jjjd krot|j|jjd rZn$|jjd ri|rdn| d | dn|jj ry| dnt dq|t |fS)z1Parse until the next block tag with a given name.Tdata%%%variable_beginr?z%(z)s variable_end block_beginz name:endtransrz:a translatable section can have only one pluralize sectionz;control structures in translatable sections are not allowedzunclosed translation blockzinternal parser error) rCrrappendrreplacerrrreos RuntimeErrorr )rrErrbufr?rrrrs<      z*InternationalizationExtension._parse_blockrrrervars_referencedrc Cs|jj}|s|s|dd}|r|dd}|dur.tdd}t|t|ggdd} ntdd} t| t|t||ggdd} |rc|D]\} } |rW| dkrWqL| j t | | qLnt | } |rzt | t dd |D} t| gS) z/Generates a useful node from the data provided.rrNrrrrocSs"g|] \}}tt||qSr)rPairConst).0rrrrr 6sz.)r2r~rrrrPritemsrMrr^MarkSafeIfAutoescapeModDictOutput) rrrrerrrrrrrrrrrrrsB         z(InternationalizationExtension._make_noder)NNN)rrrN)%rr r!rRr0rr4r5rXrrrCallabler"r#rrr)rYrTemplateSequenceIteratorTuplerr[r\rGrPatternrrrr]rr __classcell__rrrrrws     . & s % rwc@s*eZdZdZdhZdddejfddZdS) ExprStmtExtensionzrAdds a `do` tag to Jinja that works like the print statement just that it doesn't print the return value. dorErrcCs"tjt|jjd}||_|S)NrI)rExprStmtrrCrH parse_tupler)rrErrrrrGFs zExprStmtExtension.parseN)rr r!rRr0rrrGrrrrr?src@s8eZdZdZddhZdddejejej ffddZ d S) LoopControlExtensionz/Adds break and continue to the template engine.breakcontinuerErrcCs0t|j}|jdkrtj|jdStj|jdS)NrrI)rrCrrBreakrHContinue)rrErrrrrGQs  zLoopControlExtension.parseN) rr r!rRr0r5rYrrrrGrrrrrLs$rc&eZdZdeddffdd ZZS) WithExtensionr2rNc t|tjdtdddS)NzZThe 'with' extension is deprecated and will be removed in Jinja 3.1. This is built in now. stacklevelrr4warningswarnDeprecationWarningr3rrrr4Y  zWithExtension.__init__rr r!rr4rrrrrrXrcr)AutoEscapeExtensionr2rNcr)Nz`The 'autoescape' extension is deprecated and will be removed in Jinja 3.1. This is built in now.rrrr3rrrr4drzAutoEscapeExtension.__init__rrrrrrcrrc@s<eZdZdZdhZdddejfddZdede fd d Z d S) DebugExtensionaA ``{% debug %}`` tag that dumps the available variables, filters, and tests. .. code-block:: html+jinja
{% debug %}
.. code-block:: text {'context': {'cycler': , ..., 'namespace': }, 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd', ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'], 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined', ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']} .. versionadded:: 2.11.0 debugrErrcCs8|jdj}t}|jd|g|d}tj|g|dS)Nz name:debug_renderrI)rCrrHrContextReferencerQr)rrErHr%resultrrrrGszDebugExtension.parser%cCs8|t|jjt|jjd}tj|dddS)N)r%filterstestsrT)depthcompact)get_allsortedr2rkeysrpprintpformat)rr%rrrrrs zDebugExtension._renderN) rr r!rRr0rrrGr r"rrrrrrns rTastr babel_styleccs|tjD]v}t|jtjr|jj|vrqg}|jD]}t|tjr1t|j t r1| |j q| dq|j D]}| dq:|j durL| d|jdurV| d|setdd|D}|sdqnt|dkrp|d}nt|}|j|jj|fVqdS)aExtract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`. This allows Babel to figure out what you really meant if you are using gettext functions that allow keyword arguments for placeholder expansion. If you don't want that behavior set the `babel_style` parameter to `False` which causes only strings to be returned and parameters are always stored in tuples. As a consequence invalid gettext calls (calls without a single string parameter or string parameters after non-string parameters) are skipped. This example explains the behavior: >>> from jinja2 import Environment >>> env = Environment() >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}') >>> list(extract_from_ast(node)) [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))] >>> list(extract_from_ast(node, babel_style=False)) [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))] For every string found this function yields a ``(lineno, function, message)`` tuple, where: * ``lineno`` is the number of the line on which the string was found, * ``function`` is the name of the ``gettext`` function used (if the string was extracted from embedded Python code), and * ``message`` is the string, or a tuple of strings for functions with multiple string arguments. This extraction function operates on the AST and is because of that unable to extract any comments. For comment support you have to use the babel extraction interface or extract comments yourself. Ncss|] }|dur|VqdSrr)rxrrr sz#extract_from_ast..rr)find_allrrPrrrr?rLrrr"rrMrNrOtuplelenrH)rrr rstringsargr(outrrrrs6+            rc@sneZdZdZdejejeeefdejeddfddZ dedej efd d Z d edej efd d Z dS)_CommentFinderzHelper class to find comments in a token stream. Can only find comments for gettext calls forwards. Once the comment from line 4 is found, a comment for line 1 will not return a usable value. tokens comment_tagsrNcCs||_||_d|_d|_dS)Nr)rroffset last_lineno)rrrrrrr4s z_CommentFinder.__init__rc Csz>t|j|j|D]-\}}}|dvr8z |dd\}}Wn ty'Yq w||jvr8|gW||_Sq gW||_S||_w)N)comment linecommentr)reversedrrsplit ValueErrorrrstrip)rrr( token_type token_valueprefixrrrrfind_backwardss   z_CommentFinder.find_backwardsrHcCsd|jr|j|kr gSt|j|jdD]\}\}}}||kr)||j|Sq|t|jSr)rr enumeraterrr r)rrHidx token_linenor(rrr find_commentss"z_CommentFinder.find_comments) rr r!rRr5rrr#r"r4r\r r$rrrrrs rfileobjkeywordsroptionsccsi}|dddD]}|}|sq d|t|<q t|vr$d|t<d dtjttfdtdtd tfd d }||d d }t |dt j |dt j |dt j |dt j|dt j|dt j|dpit j|dppt j||dt j||dt jt j||dt jt|ddd}||drd |jd<||drd |_||dd} z|| } t||| } Wn t y|sĂYdSwt!| |} t"| |D]\} }}| ||| #| fVqdS)!aBabel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best preceding comment that begins with one of the keywords. For best results, make sure to not have more than one gettext call in one line of code and the matching comment in the same line or the line before. .. versionchanged:: 2.5.1 The `newstyle_gettext` flag can be set to `True` to enable newstyle gettext calls. .. versionchanged:: 2.7 A `silent` option can now be provided. If set to `False` template syntax errors are propagated instead of being ignored. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results. :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples. (comments will be empty currently) extensions,NFr'rdefaultrcSs||t|dvS)N>1onyestrue)getr"lower)r'rr+rrrgetbool?r/zbabel_extract..getboolsilentTblock_start_stringblock_end_stringvariable_start_stringvariable_end_stringcomment_start_stringcomment_end_stringline_statement_prefixline_comment_prefix trim_blocks lstrip_blockskeep_trailing_newliner) cache_size auto_reloadrrr~encodingzutf-8)F)$r0rrr rwr5Mappingr"rrrBLOCK_START_STRINGBLOCK_END_STRINGVARIABLE_START_STRINGVARIABLE_END_STRINGCOMMENT_START_STRINGCOMMENT_END_STRINGLINE_STATEMENT_PREFIXLINE_COMMENT_PREFIX TRIM_BLOCKS LSTRIP_BLOCKSNEWLINE_SEQUENCEKEEP_TRAILING_NEWLINEr rr~readdecoderGlistlexrBrrrr$)r%r&rr'r(extension_namer2r3r2r>rrfinderrHrcrrrr babel_extract sZ%&                rU)JrRrretypingr5r markupsaferr)rrr2r exceptionsrrruntimer r r utilsr r TYPE_CHECKINGtyping_extensionstelexerrrrErProtocolrr$rYrr)rr"rTcompilerr*rjrbrrkr#rsrurvrwrrrrrrrrrrXrrBinaryIOrr\rUi18nr loopcontrolswith_rgrrrrrs               m (,*  K    *. O(0 ]