o knh|@s:UdZddlZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z dd l mZdd lmZdd lmZdd lmZdd lmZddlmZejrddlZddlmZddlmZddlmZGdddejZGdddeZ ej!ee 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&Z/d"ej,e%e%ge%fdej,de%ffd'd(Z0d"ej,e%e%e%e.ge%fdej,de%ffd)d*Z1Gd+d,d,e)Z2Gd-d.d.e)Z3Gd/d0d0e)Z4Gd1d2d2e)Z5e#d3fd4e j6d5ej7e%d6e8dej9ej$e.e%ej!ej:e%ej$ej:e%dffffd7d8Z;Gd9d:d:Zej>e%ej*fdej9ej$e.e%ej!ej:e%ej$ej:e%dffej?e%ff d?d@Z@e2ZAe3ZBe4ZCe5ZDdS)Az2Extension API for adding custom tags and behavior.N)Markup)defaults)nodes) Environment)TemplateAssertionError)TemplateSyntaxError)concat)Context) Undefined) import_string) pass_context)Token) TokenStream)Parserc@s8eZdZdedefddZdedededefdd Zd S) _TranslationsBasicmessagereturncCdSN)selfrrr5/usr/local/lib/python3.10/dist-packages/jinja2/ext.pygettextz_TranslationsBasic.gettextsingularpluralncCrrr)rrrrrrrngettextz_TranslationsBasic.ngettextN)__name__ __module__ __qualname__strrintrrrrrrsrc @s@eZdZdededefddZdededededef d d Zd S) _TranslationsContextcontextrrcCrrr)rr&rrrrpgettext"rz_TranslationsContext.pgettextrrrcCrrr)rr&rrrrrr npgettext$sz_TranslationsContext.npgettextN)r r!r"r#r'r$r(rrrrr%!sr%)_rrr'r(.GETTEXT_FUNCTIONSz\s*\n\s*c@s`eZdZUdZejeed<d&ddZe Z ej eed<dZ d e ddfd d Zd e dd fd dZ d'dedejedejedefddZdddejdejdffddZdddejejejejffddZ d'dedejedejfddZ     d(ded ejejejd!ejejejd"ejejd#ejejdejedejfd$d%ZdS)) ExtensionagExtensions can be used to add extra functionality to the Jinja template system at the parser level. Custom extensions are bound to an environment but may not store environment specific data on `self`. The reason for this is that an extension can be bound to another environment (for overlays) by creating a copy and reassigning the `environment` attribute. As extensions are created by the environment they cannot accept any arguments for configuration. One may want to work around that by using a factory function, but that is not possible as extensions are identified by their import name. The correct way to configure the extension is storing the configuration values on the environment. Because this way the environment ends up acting as central configuration storage the attributes may clash which is why extensions have to ensure that the names they choose for configuration are not too generic. ``prefix`` for example is a terrible name, ``fragment_cache_prefix`` on the other hand is a good name as includes the name of the extension (fragment cache). identifierrNcCs|jd|j|_dS)N.)r!r r,)clsrrr__init_subclass__LzExtension.__init_subclass__tagsd environmentcCs ||_dSr)r3rr3rrr__init__Ys zExtension.__init__zte.SelfcCs$t|j}|j|j||_|S)z=Create a copy of this extension bound to another environment.)object__new__ __class____dict__updater3)rr3rvrrrbind\s zExtension.bindsourcenamefilenamecC|S)zThis method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source. r)rr=r>r?rrr preprocesscszExtension.preprocessstreamrrcCr@)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)rrBrrr 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)rrDrrrparsevszExtension.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) rG)rExtensionAttributer,)rr>rGrrrattr~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`. NrH)rCallrJ)rr>rKrLrMrNrGrrr call_methods  zExtension.call_method)rNr)NNNNN) r r!r"__doc__tClassVarr#__annotations__r/setr1Setpriorityrr5r<OptionalrAUnionIterablerCrNodeListrFr$rIrJExprKeywordrOrPrrrrr+7sh     &     r+ __contextrKrLrcOs|j|dg|Ri|S)Nr)callresolve)r_rKrLrrr_gettext_aliassrbfuncc s(tdtdtdtjdtffdd }|S)Nr___string variablesrcs$||}|jjrt|}||Sr)r`eval_ctx autoescaper)r_rdrer;rcrrrs z"_make_new_gettext..gettextr r r#rRAny)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$rRrj)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 d0dd d eje ddfd d Z d0d eje ddfd dZ   d1dej e ge fdej e e ege fd eje dejej e e ge fdejej e e e ege fddf ddZd2ddZefdeje ejfdeje dejejee ejeje ejeje dffffddZdddejejejejffddZefd e d!eje de fd"d#Zddd$e dejeje e ffd%d&Zd'e d(eje d)eje d*ej e ej!fd+ejej!d,e d-e dej"fd.d/Z#Z$S)3InternationalizationExtensionz-This extension adds gettext support to Jinja.transr3rNcs:t|t|jd<|j|j|j|j|j|j dddS)Nr)F)install_gettext_translationsinstall_null_translationsinstall_gettext_callablesuninstall_gettext_translationsextract_translationsnewstyle_gettext) superr5rbglobalsextend_install _install_null_install_callables _uninstall_extractr4r8rrr5s   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'csrcSr@rr)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()r3r~rkrsrurvrr:)rrrrr'r(rrrr<s z0InternationalizationExtension._install_callablescCsdD] }|jj|dqdSr)r3rpop)rrkeyrrrrTsz(InternationalizationExtension._uninstallr=gettext_functions.cCs t|tr |j|}t||Sr) isinstancer#r3rFextract_from_ast)rr=rrrrrXs   z&InternationalizationExtension._extractrDrc Cs&t|jj}d}|jd}|dur|j}d}d}d}i}d} |jjjdkr|r.|jd|jdr5nx|jd} | j|vrN|j d| jd | jt d |jjjd krdt|j| || j<} n| durs| jd vrs| jd k} qt | jd|| j<} |durt| t jrt dd}||| j<t t dd| }n| }| jdk}|jjjdks&|jdd} d} t}||d\}}|r|||durt |dd}|ddk}|jjdr/d} t|j|jjjdkr|jd} | j|vr |j d| jd| jt d || j}| jdk}|jd||d\}} t|j||nt|j|D]}||vrEt |d||<q6| sMd}n |durX| d|| durc|jjd} | rs||}| rs|| } ||| |||t||o| }|||dur||gS|S)zParse a translatable tag.NstringF block_endcommacolonr>ztranslatable variable z defined twice.)excassign)trimmed notrimmedrload_transstoreroTrzname:pluralizezunknown variable z for pluralizationzpluralize without variablesext.i18n.trimmed)nextrBrGnext_ifvaluecurrenttypeexpectskip_iffailrparse_expressionrNamerrOAssignrU _parse_blockr:testr3policies_trim_whitespace _make_nodebool set_lineno)rrDrGr& context_token plural_exprplural_expr_assignmentnum_called_numrertokenvarr have_plural referencedsingular_namesr plural_namesr>noderrrrFcs               %                    z#InternationalizationExtension.parser_ws_recCs|d|S)N )substrip)rrrrrrrrz.InternationalizationExtension._trim_whitespaceallow_pluralizecCs4g}g} |jjjdkr||jjjddt|jnu|jjjdkrFt|j|jdj}|||d|d|jd nM|jjjd krt|j|jjjdkr^|jjjnd }|d kren/|d krr|rln(|dn |dkr{|d|d|dn|jj r|dnt dq|t |fS)z1Parse until the next block tag with a given name.Tdata%%%variable_beginr>z%(z)s variable_end block_beginNendtrans pluralizez:a translatable section can have only one pluralize sectionrxz6trans blocks can't be nested; did you mean `endtrans`?zBcontrol structures in translatable sections are not allowed; saw ``zunclosed translation blockzinternal parser error) rBrrappendrreplacerrreos RuntimeErrorr )rrDrrbufr> block_namerrrrsP       &z*InternationalizationExtension._parse_blockrrr&rervars_referencedrcCs|jj}|s|s|dd}|r|dd}d} t|g} |dur0| dt|d| } |durCd| } | t||ftt| d| gdd} |rm| D]\} } |ra| d kraqV| j t | | qVnt | } |rt| td d | D} t| gS) z/Generates a useful node from the data provided.rrrNrrrrrocSs"g|] \}}tt||qSr)rPairConst).0rrrrr Esz.)r3r~rrrinsertrrOritemsrLrr^MarkSafeIfAutoescapeModDictOutput)rrrr&rerrrr func_name func_argsrrrrrrrs>         z(InternationalizationExtension._make_noder)NNN)rrrN)%r r!r"rQr1rr5rRrXrrrCallabler#r$rrr*rYrTemplateSequenceIteratorTuplerr[r\rFrPatternrrrr]rr __classcell__rrrrrws     . & z /  rwc@s*eZdZdZdhZdddejfddZdS) ExprStmtExtensionzrAdds a `do` tag to Jinja that works like the print statement just that it doesn't print the return value. dorDrrcCs"tjt|jjd}||_|S)NrH)rExprStmtrrBrG parse_tupler)rrDrrrrrFUs zExprStmtExtension.parseN)r r!r"rQr1rrrFrrrrrNsrc@s8eZdZdZddhZdddejejej ffddZ d S) LoopControlExtensionz/Adds break and continue to the template engine.breakcontinuerDrrcCs0t|j}|jdkrtj|jdStj|jdS)NrrH)rrBrrBreakrGContinue)rrDrrrrrF`s  zLoopControlExtension.parseN) r r!r"rQr1rRrYrrrrFrrrrr[s$rc@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 debugrDrrcCs8|jdj}t}|jd|g|d}tj|g|dS)Nz name:debug_renderrH)rBrrGrContextReferencerPr)rrDrGr&resultrrrrF~szDebugExtension.parser&cCs8|t|jjt|jjd}tj|dddS)N)r&filterstestsT)depthcompact)get_allsortedr3rkeysrpprintpformat)rr&rrrrrs zDebugExtension._renderN) r r!r"rQr1rrrFr r#rrrrrrgs 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_allrrOrrrr>rKrrr#rrLrMrNtuplelenrG)rrrrstringsargr)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)rrrrrrr5s 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_backwardsrGcCsd|jr|j|kr gSt|j|jdD]\}\}}}||kr)||j|Sq|t|jSr)rr enumeraterrrr )rrGidx token_linenor)rrr find_commentss"z_CommentFinder.find_comments) r r!r"rQrRrrr$r#r5r\rrrrrrr s r fileobjkeywordsroptionsccsi}|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&rrrgetbool8r0zbabel_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)$r+rrr rwrRMappingr#rrrBLOCK_START_STRINGBLOCK_END_STRINGVARIABLE_START_STRINGVARIABLE_END_STRINGCOMMENT_START_STRINGCOMMENT_END_STRINGLINE_STATEMENT_PREFIXLINE_COMMENT_PREFIX TRIM_BLOCKS LSTRIP_BLOCKSNEWLINE_SEQUENCEKEEP_TRAILING_NEWLINErrr~readdecoderFlistlexrArr rr)r r!rr"r#extension_namer-r.r3r=rrfinderrGrcrrrr babel_extractsZ%&                rP)ErQrretypingrR markupsaferr$rrr3r exceptionsrrruntimer r r utilsr r TYPE_CHECKINGtyping_extensionstelexerrrrDrProtocolrr%rYrr*rr#rTcompilerr+rjrbrrkr$rsrurvrwrrrrrrrrXrr BinaryIOrr\rPi18nr loopcontrolsrrrrrs               m (,*  Z  *. O(0 ]