3

X'ícpjã@sdZddlZddlZddlmZddlZddlmZmZm	Z	m
Z
mZddlm
Z
mZmZddlmZdZddd%dd&d'd(dd*d,dœ
Zd-gZdZdd„Zdd„Zdedefdddfdd„Zd.dd„Zefddfdd„Zefddfdd„Zdd„Zdd „Zd!d"„Zd#d$„ZdS)/af
    babel.messages.extract
    ~~~~~~~~~~~~~~~~~~~~~~

    Basic infrastructure for extracting localizable messages from source files.

    This module defines an extensible system for collecting localizable message
    strings from a variety of sources. A native extractor for Python source
    files is builtin, extractors for other sources can be added using very
    simple plugins.

    The main entry points into the extraction functionality are the functions
    `extract_from_dir` and `extract_from_file`.

    :copyright: (c) 2013-2022 by the Babel Team.
    :license: BSD, see LICENSE for more details.
éN)Úrelpath)Úgenerate_tokensÚCOMMENTÚNAMEÚOPÚSTRING)Úparse_encodingÚparse_future_flagsÚ	pathmatch)Údedentzbabel.extractorséééÚc)
Ú_ÚgettextÚngettextZugettextZ	ungettextÚdgettextÚ	dngettextZN_ZpgettextZ	npgettextú**.pyÚpythonz‹%s: warning: Empty msgid.  It is reserved by GNU gettext: gettext("") returns the header entry with meta information, not the empty string.cs"‡fdd„}t||ƒ|dd…<dS)z‹Helper function for `extract` that strips comment tags from strings
    in a list of comment lines.  This functions operates in-place.
    cs0x*ˆD]"}|j|ƒr|t|ƒd…jƒSqW|S)N)Ú
startswithÚlenÚstrip)ÚlineÚtag)Útags©ú7/tmp/pip-build-gk9425m9/babel/babel/messages/extract.pyÚ_strip6s

z#_strip_comment_tags.<locals>._stripN)Úmap)Úcommentsrrr)rrÚ_strip_comment_tags2sr"cCs"tjj|ƒ}|jdƒp|jdƒS)NÚ.r)ÚosÚpathÚbasenamer)ÚdirpathÚsubdirrrrÚdefault_directory_filter>sr)Fc
#sÂ|dkrtjƒ}|dkri}ˆdkr(t‰tjj|ƒ}xˆtj|ƒD]z\‰}	}
‡‡fdd„|	Dƒ|	dd…<|	jƒ|
jƒxB|
D]:}tjjˆ|ƒjtj	dƒ}t
||||||||dEdHq|Wq@WdS)a$
Extract messages from any source files found in the given directory.

    This function generates tuples of the form ``(filename, lineno, message,
    comments, context)``.

    Which extraction method is used per file is determined by the `method_map`
    parameter, which maps extended glob patterns to extraction method names.
    For example, the following is the default mapping:

    >>> method_map = [
    ...     ('**.py', 'python')
    ... ]

    This basically says that files with the filename extension ".py" at any
    level inside the directory should be processed by the "python" extraction
    method. Files that don't match any of the mapping patterns are ignored. See
    the documentation of the `pathmatch` function for details on the pattern
    syntax.

    The following extended mapping would also use the "genshi" extraction
    method on any file in "templates" subdirectory:

    >>> method_map = [
    ...     ('**/templates/**.*', 'genshi'),
    ...     ('**.py', 'python')
    ... ]

    The dictionary provided by the optional `options_map` parameter augments
    these mappings. It uses extended glob patterns as keys, and the values are
    dictionaries mapping options names to option values (both strings).

    The glob patterns of the `options_map` do not necessarily need to be the
    same as those used in the method mapping. For example, while all files in
    the ``templates`` folders in an application may be Genshi applications, the
    options for those files may differ based on extension:

    >>> options_map = {
    ...     '**/templates/**.txt': {
    ...         'template_class': 'genshi.template:TextTemplate',
    ...         'encoding': 'latin-1'
    ...     },
    ...     '**/templates/**.html': {
    ...         'include_attrs': ''
    ...     }
    ... }

    :param dirname: the path to the directory to extract messages from.  If
                    not given the current working directory is used.
    :param method_map: a list of ``(pattern, method)`` tuples that maps of
                       extraction method names to extended glob patterns
    :param options_map: a dictionary of additional options (optional)
    :param keywords: a dictionary mapping keywords (i.e. names of functions
                     that should be recognized as translation functions) to
                     tuples that specify which of their arguments contain
                     localizable strings
    :param comment_tags: a list of tags of translator comments to search for
                         and include in the results
    :param callback: a function that is called for every file that message are
                     extracted from, just before the extraction itself is
                     performed; the function is passed the filename, the name
                     of the extraction method and and the options dictionary as
                     positional arguments, in that order
    :param strip_comment_tags: a flag that if set to `True` causes all comment
                               tags to be removed from the collected comments.
    :param directory_filter: a callback to determine whether a directory should
                             be recursed into. Receives the full directory path;
                             should return True if the directory is valid.
    :see: `pathmatch`
    Ncs"g|]}ˆtjjˆ|ƒƒr|‘qSr)r$r%Újoin)Ú.0r()Údirectory_filterÚrootrrú
<listcomp>sz$extract_from_dir.<locals>.<listcomp>ú/)r')r$Úgetcwdr)r%ÚabspathÚwalkÚsortr*ÚreplaceÚsepÚcheck_and_call_extract_file)
ÚdirnameÚ
method_mapÚoptions_mapÚkeywordsÚcomment_tagsÚcallbackÚstrip_comment_tagsr,ZabsnameÚdirnamesÚ	filenamesÚfilenameÚfilepathr)r,r-rÚextract_from_dirDs,O
rBc	cst||ƒ}x€|D]x\}	}
t|	|ƒs$qi}x"|jƒD]\}}
t||ƒr2|
}q2W|r\|||
|ƒx(t|
|||||dD]}|f|VqrWPqWdS)aChecks if the given file matches an extraction method mapping, and if so, calls extract_from_file.

    Note that the extraction method mappings are based relative to dirpath.
    So, given an absolute path to a file `filepath`, we want to check using
    just the relative path from `dirpath` to `filepath`.

    Yields 5-tuples (filename, lineno, messages, comments, context).

    :param filepath: An absolute path to a file that exists.
    :param method_map: a list of ``(pattern, method)`` tuples that maps of
                       extraction method names to extended glob patterns
    :param options_map: a dictionary of additional options (optional)
    :param callback: a function that is called for every file that message are
                     extracted from, just before the extraction itself is
                     performed; the function is passed the filename, the name
                     of the extraction method and and the options dictionary as
                     positional arguments, in that order
    :param keywords: a dictionary mapping keywords (i.e. names of functions
                     that should be recognized as translation functions) to
                     tuples that specify which of their arguments contain
                     localizable strings
    :param comment_tags: a list of tags of translator comments to search for
                         and include in the results
    :param strip_comment_tags: a flag that if set to `True` causes all comment
                               tags to be removed from the collected comments.
    :param dirpath: the path to the directory to extract messages from.
    :return: iterable of 5-tuples (filename, lineno, messages, comments, context)
    :rtype: Iterable[tuple[str, int, str|tuple[str], list[str], str|None]
    )r:r;Úoptionsr=N)rr
ÚitemsÚextract_from_file)rAr8r9r<r:r;r=r'r@ÚpatternÚmethodrCZopatternZodictZ
message_tuplerrrr6±s$!


r6cCs8|dkrgSt|dƒ}tt||||||ƒƒSQRXdS)aExtract messages from a specific file.

    This function returns a list of tuples of the form ``(lineno, message, comments, context)``.

    :param filename: the path to the file to extract messages from
    :param method: a string specifying the extraction method (.e.g. "python")
    :param keywords: a dictionary mapping keywords (i.e. names of functions
                     that should be recognized as translation functions) to
                     tuples that specify which of their arguments contain
                     localizable strings
    :param comment_tags: a list of translator tags to search for and include
                         in the results
    :param strip_comment_tags: a flag that if set to `True` causes all comment
                               tags to be removed from the collected comments.
    :param options: a dictionary of additional options (optional)
    :returns: list of tuples of the form ``(lineno, message, comments, context)``
    :rtype: list[tuple[int, str|tuple[str], list[str], str|None]
    ÚignoreÚrbN)ÚopenÚlistÚextract)rGr@r:r;rCr=ÚfileobjrrrrEês
rEccs˜d}t|ƒr|}nÒd|ks"d|kr|d|krT|jdƒ}|d|…||dd…}}	n|jddƒ\}}	tt|ii|	gƒ|	ƒ}nhyddlm}
Wntk
r Yn&Xx"|
jt	|ƒD]}|j
dd}Pq°W|dkrättt
d	œ}|j|ƒ}|dkrøtd
|ƒ‚|||jƒ||pid}
x~|
D]t\}}}}|r>||p:d}nd}t|ttfƒsX|g}|sbqd}g}d}t|ƒ}xd|D]\}t|tƒr ||dd}q|||kr°d}P||d}|dkrÌd}P|j|ƒq|W|ræqt|dtƒr|dd}n|dd}||sRd
t|dƒr0|jp2d|f}tjjt|dƒqt|ƒ}t|ƒdkrp|d}|r€t||ƒ||||fVqWdS)aªExtract messages from the given file-like object using the specified
    extraction method.

    This function returns tuples of the form ``(lineno, message, comments, context)``.

    The implementation dispatches the actual extraction to plugins, based on the
    value of the ``method`` parameter.

    >>> source = b'''# foo module
    ... def run(argv):
    ...    print(_('Hello, world!'))
    ... '''

    >>> from io import BytesIO
    >>> for message in extract('python', BytesIO(source)):
    ...     print(message)
    (3, u'Hello, world!', [], None)

    :param method: an extraction method (a callable), or
                   a string specifying the extraction method (.e.g. "python");
                   if this is a simple name, the extraction function will be
                   looked up by entry point; if it is an explicit reference
                   to a function (of the form ``package.module:funcname`` or
                   ``package.module.funcname``), the corresponding function
                   will be imported and used
    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a dictionary mapping keywords (i.e. names of functions
                     that should be recognized as translation functions) to
                     tuples that specify which of their arguments contain
                     localizable strings
    :param comment_tags: a list of translator tags to search for and include
                         in the results
    :param options: a dictionary of additional options (optional)
    :param strip_comment_tags: a flag that if set to `True` causes all comment
                               tags to be removed from the collected comments.
    :raise ValueError: if the extraction method is not registered
    :returns: iterable of tuples of the form ``(lineno, message, comments, context)``
    :rtype: Iterable[tuple[int, str|tuple[str], list[str], str|None]
    Nú:r#rr)Úworking_setT)Úrequire)rHrZ
javascriptzUnknown extraction method %r)rCFz%s:%iÚnamez	(unknown)Ú
)r)r)ÚcallableÚrfindÚsplitÚgetattrÚ
__import__Ú
pkg_resourcesrOÚImportErrorÚiter_entry_pointsÚ
GROUP_NAMEÚloadÚextract_nothingÚextract_pythonÚextract_javascriptÚgetÚ
ValueErrorÚkeysÚ
isinstancerKÚtuplerÚappendÚhasattrrQÚsysÚstderrÚwriteÚempty_msgid_warningr")rGrMr:r;rCr=ÚfuncZlastdotÚmoduleÚattrnamerOZentry_pointÚbuiltinÚresultsÚlinenoÚfuncnameÚmessagesr!ÚspecÚcontextZmsgsÚinvalidÚ
last_indexÚindexÚmessageZfirst_msg_indexÚwhererrrrLs„)
 






rLcCsgS)zdPseudo extractor that does not actually extract anything, but simply
    returns an empty list.
    r)rMr:r;rCrrrr]Šsr]c#s2d}}}d}g}g}	g}
d}}d}
tˆƒp:|jddƒ‰tˆˆƒ}‡‡fdd„}t|ƒ}xÎ|D]Ä\}}\}}}}|dkr–|tkr–|dkr–d
}qd|tkrÂ|dkrÂ|r°d}qd|rÀ|}|d7}qd|rÞ|tkrÞ|dkrÞd}qdqd|dkoì|tkr^|dd…jƒ}|r,|
dd
|dkr,|
j||fƒqdx.|D]&}
|j	|
ƒr2d
}|
j||fƒPq2Wqd|rØ|d
krØ|tko~||k}|tkr”|dksš|rF|r¼|	jdj
|ƒƒ|dd…=n
|	jdƒt|	ƒdkrÞt|	ƒ}	n|	d
}	|
r|
dd
|dkrg}
|||	dd„|
DƒfVd}}}d}g}	g}
d}|rÖ|}n|t
krrt|ˆ|ƒ}|dk	rÖ|j|ƒnd|tkr*|dkr*|r¨|	jdj
|ƒƒ|dd…=n
|	jdƒ|
r*|
jƒ\}}|
j|d|fƒqd|d
kr|tkr|dkr|d8}qd|r|dkrd}qd|tkrd||krd|}qdWdS)acExtract messages from Python source code.

    It returns an iterator yielding tuples in the following form ``(lineno,
    funcname, message, comments)``.

    :param fileobj: the seekable, 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)
    :rtype: ``iterator``
    NrFÚencodingzUTF-8csˆjƒjˆƒS)N)ÚreadlineÚdecoder)rzrMrrÚ<lambda>ªsz extract_python.<locals>.<lambda>ÚdefÚclassTú(rNrú)ÚcSsg|]}|d‘qS)rr)r+Úcommentrrrr.àsz"extract_python.<locals>.<listcomp>ú,éÿÿÿÿr…)r~rr…r…r…r…r…)rr`r	rrrrrrerr*rrdrÚ_parse_python_stringÚpop)rMr:r;rCrqrpÚmessage_linenoÚ
call_stackÚbufrrÚtranslator_commentsZin_defZin_translator_commentsÚcomment_tagÚfuture_flagsZ	next_lineÚtokensÚtokÚvaluerÚnestedÚvalZ
old_linenoZold_commentr)rzrMrr^‘s–









r^cCs¬tdt|ƒ›d|›ddtj|Bƒ}t|tjƒr¨|j}t|tjƒrH|jSt|tj	ƒr¨t
dd„|jDƒƒr~djdd„|jDƒƒSt
d	d„|jDƒƒr¨djd
d„|jDƒƒSdS)Nz	# coding=rRz<string>Úevalcss|]}t|tjƒVqdS)N)rcÚastÚStr)r+Únoderrrú	<genexpr>sz'_parse_python_string.<locals>.<genexpr>r‚css|]}|jVqdS)N)Ús)r+r–rrrr—scss|]}t|tjƒVqdS)N)rcr”ÚConstant)r+r–rrrr—scss|]}t|jƒVqdS)N)Ústrr)r+r–rrrr—s)
Úcompileršr”Ú
PyCF_ONLY_ASTrcÚ
ExpressionÚbodyr•r˜Ú	JoinedStrÚallÚvaluesr*)rrzrÚcoderžrrrr†sr†ccsddlm}m}m}d}}g}	d}
g}d}|jddƒ}
d}d}tdd	„|Dƒƒ}x¾||jƒj|
ƒ|jd
dƒ|jddƒ|d
D]Ž}|rÆ|rÆ|jdkrÆ|jdkrÆ|j	}||j
ƒg}	d}|dd|j	ƒ}|jdkrð|j
dkrð|rì|j	}|d7}n|dkr~|jdkr~|j
dd…jƒ}|rH|dd|j	dkrH|j|j	|fƒq€x0|D](}|j
|ƒrN|j|j	|jƒfƒPqNWnŽ|jdkr.g}|j
dd …jƒ}xˆ|D]€}|j
|ƒr¦|jƒ}|r"|djƒ|d<tdj|dd…ƒƒjƒ|dd…<x*t|ƒD]\}}|j|j	||fƒqWPq¦WnÞ|r€|dkr€|jdkrö|j
dkrö|
dk	rj|	j|
ƒt|	ƒdkr‚t|	ƒ}	n|	r’|	d}	nd}	|r¶|d!d|dkr¶g}|	dk	rØ|||	dd„|DƒfVd}}}
d}g}g}	d"}nˆ|jd#kr,||j
ƒ}|r&|
pd|}
d}n|}
nR|jdkr|j
dkrn|
dk	r^|	j|
ƒd}
n
|	jdƒd}n|j
dkrd}nŒ|dkr¬|jdkr¬|j
dkr¬|d8}n`|rÂ|d$krÂd}nJ|d%kr|jdkr|j
|kr|dks|jdks|j
dkr|j
}|}q€WdS)&a°Extract messages from JavaScript source code.

    :param fileobj: the seekable, 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)
                    Supported options are:
                    * `jsx` -- set to false to disable JSX/E4X support.
                    * `template_string` -- set to false to disable ES6 template string support.
    r)ÚTokenÚtokenizeÚunquote_stringNFrzzutf-8rcss|]}d|kVqdS)r#Nr)r+Úkwrrrr—/sz%extract_javascript.<locals>.<genexpr>ÚjsxTÚtemplate_string)r§r¨ÚdottedrQÚoperatorrr€Zlinecommentr
ZmultilinecommentrRcSsg|]}|d‘qS)rr)r+rƒrrrr.tsz&extract_javascript.<locals>.<listcomp>Ústringr‚r„ú+Úfunctionr…r…r…éþÿÿÿr…r…)r«r¨r…r…)Zbabel.messages.jslexerr£r¤r¥r`ÚanyÚreadr|ÚtyperprrrerÚ
splitlinesrr*Ú	enumeraterrd)rMr:r;rCr£r¤r¥rqrˆrrZ
last_argumentr‹Zconcatenate_nextrzZ
last_tokenr‰r©ÚtokenrrŒÚlinesÚoffsetrZ	new_valuerrrr_s¾




"









r_)rr
)rr
)r
)r
r©rr)r·r
©rr)r¸r
r)rr)N) Ú__doc__r”r$Úos.pathrrgr¤rrrrrZ
babel.utilrr	r
Útextwraprr[ZDEFAULT_KEYWORDSZDEFAULT_MAPPINGrjr"r)rBr6rErLr]r^r†r_rrrrÚ<module>sPg
7q