3
tûœ]9  ã               @   sž   d Z ddlZddlZddlmZmZ ddlmZ ddlm	Z	 d+d,d-d.d/d0dœZ
dddddddd hZf f fd!d"„ZG d#d$„ d$ejƒZd%d&„ Zd'd(„ Zd)d*„ ZdS )1z"checker for use of Python logging
é    N)ÚcheckersÚ
interfaces)Úutils)Úcheck_messagesú>Specify string format arguments as logging function parametersúlogging-not-lazyá²  Used when a logging statement has a call form of "logging.<logging method>(format_string % (format_args...))". Such calls should leave string interpolation to the logging method itself and be written "logging.<logging method>(format_string, format_args...)" so that the program may avoid incurring the cost of the interpolation in those cases in which no message will be logged. For more, see http://www.python.org/dev/peps/pep-0282/.ú(Use %s formatting in logging functions%súlogging-format-interpolationú°Used when a logging statement has a call form of "logging.<logging method>(<string formatting>)". with invalid string formatting. Use another way for format the string instead.ú;Unsupported logging format character %r (%#02x) at index %dúlogging-unsupported-formatúWUsed when an unsupported format character is used in a logging statement format string.ú<Logging format string ends in middle of conversion specifierúlogging-format-truncatedú`Used when a logging statement format string terminates before the end of a conversion specifier.ú,Too many arguments for logging format stringúlogging-too-many-argsú>Used when a logging format string is given too many arguments.ú.Not enough arguments for logging format stringúlogging-too-few-argsú=Used when a logging format string is given too few arguments.)ZW1201ZW1202ZE1200ZE1201ZE1205ZE1206ÚcriticalÚdebugÚerrorÚ	exceptionÚfatalÚinfoÚwarnÚwarningc             C   s@   t | tjƒo>t | jtjƒo>|r*| jj|kndo>|r<| j|kS dS )aÀ  Determines if a BoundMethod node represents a method call.

    Args:
      func (astroid.BoundMethod): The BoundMethod AST node to check.
      types (Optional[String]): Optional sequence of caller type names to restrict check.
      methods (Optional[String]): Optional sequence of method names to restrict check.

    Returns:
      bool: true if the node represents a method call for the given type and
      method names, False otherwise.
    T)Ú
isinstanceÚastroidÚBoundMethodÚboundZInstanceÚname)ÚfuncÚtypesÚmethods© r(   ú9/tmp/pip-build-fn42xldr/pylint/pylint/checkers/logging.pyÚis_method_callW   s    r*   c               @   s–   e Zd ZdZejZdZeZ	dd!ddddœfdd	d
dd	ddgddœffZ
dd„ Zdd„ Zdd„ ZeeŽ dd„ ƒZdd„ Zedd„ ƒZdd„ Zdd„ Zd S )"ÚLoggingCheckerz!Checks use of the logging module.Úloggingzlogging-modulesÚcsvz<comma separated list>zcLogging modules to check that the string format arguments are in logging function parameter format.)ÚdefaultÚtypeÚmetavarÚhelpzlogging-format-styleÚoldÚchoicez"<old (%) or new ({) or fstr (f'')>ÚnewÚfstrz‹Format style used to check logging format string. `old` means using % formatting, `new` is for `{}` formatting,and `fstr` is for f-strings.)r.   r/   r0   Úchoicesr1   c             C   s”   t ƒ | _| jj}| jj| _ddddœ}d}| jdkr8d}|| j |f| _t |ƒ| _i | _x6|D ].}|j	dd	ƒ}t
|ƒd	kr^|d	 | j|d
 < q^W dS )z?Clears any state left in this checker from last module checked.ú%Ú{zf-string)r2   r4   r5   Ú r2   z' and pass the % parameters as argumentsÚ.é   r   N)ÚsetÚ_logging_namesÚconfigZlogging_modulesZlogging_format_styleÚ_format_styleÚ_format_style_argsÚ_logging_modulesÚ_from_importsÚrsplitÚlen)ÚselfÚnodeZlogging_modsZformat_stylesZformat_style_helpZlogging_modÚpartsr(   r(   r)   Úvisit_module‹   s    



zLoggingChecker.visit_modulec             C   sV   y<| j |j }x*|jD ] \}}||kr| jj|p2|ƒ qW W n tk
rP   Y nX dS )z;Checks to see if a module uses a non-Python logging module.N)rB   ÚmodnameÚnamesr=   ÚaddÚKeyError)rE   rF   Zlogging_nameÚmoduleÚas_namer(   r(   r)   Úvisit_importfrom¢   s    zLoggingChecker.visit_importfromc             C   s2   x,|j D ]"\}}|| jkr| jj|p&|ƒ qW dS )z<Checks to see if this module uses Python's built-in logging.N)rJ   rA   r=   rK   )rE   rF   rM   rN   r(   r(   r)   Úvisit_import¬   s    
zLoggingChecker.visit_importc                sL   ‡ ‡fdd„}‡ fdd„}|ƒ r*ˆ j j}n|ƒ \}}|s<dS ˆjˆ |ƒ dS )z Checks calls to logging methods.c                  s.   t ˆ jtjƒo,t ˆ jjtjƒo,ˆ jjjˆjkS )N)r    r%   r!   Ú	AttributeÚexprÚNamer$   r=   r(   )rF   rE   r(   r)   Úis_logging_name¶   s    z2LoggingChecker.visit_call.<locals>.is_logging_namec                 s„   yfx`ˆ j jƒ D ]R} t| tjƒr| jj}t|tjƒr|jƒ dksTt	dd„ |j
ƒ D ƒƒrd| jjfS qW W n tjjk
r~   Y nX dS )Nzlogging.Loggerc             s   s   | ]}|j ƒ d kV  qdS )zlogging.LoggerN)Úqname)Ú.0Zancestorr(   r(   r)   ú	<genexpr>Å   s   zELoggingChecker.visit_call.<locals>.is_logger_class.<locals>.<genexpr>TF)FN)r%   Zinferr    r!   r"   Z_proxiedÚparentÚClassDefrU   ÚanyZ	ancestorsr$   Ú
exceptionsZInferenceError)ÚinferredrX   )rF   r(   r)   Úis_logger_class½   s    z2LoggingChecker.visit_call.<locals>.is_logger_classN)r%   ÚattrnameÚ_check_log_method)rE   rF   rT   r]   r$   Úresultr(   )rF   rE   r)   Ú
visit_call²   s    

zLoggingChecker.visit_callc                sB  |dkr,|j s"|js"t|jƒdk r&dS d}n*|tkrR|j sH|jsH|j rLdS d}ndS t|j| tjƒrÀ|j| }|jdk}|jdkr¬t	‡ fdd	„|j
|jfD ƒƒ}|dk}|r¾ˆ jd
|d� n~t|j| tjƒräˆ j|j| ƒ nZt|j| tjƒ�rˆ j||ƒ n8t|j| tjtjfƒ�r>ˆ jdk�r>ˆ jd|ˆ jd� dS )z9Checks calls to logging.log(level, format, *format_args).Úlogé   Nr;   r   r7   ú+c             3   s"   | ]}ˆ j tj|ƒƒrd V  qdS )r;   N)Ú_is_operand_literal_strr   Ú
safe_infer)rV   Úoperand)rE   r(   r)   rW   ì   s   z3LoggingChecker._check_log_method.<locals>.<genexpr>zlogging-not-lazy)rF   r5   zlogging-format-interpolation)rF   Úargs)ZstarargsÚkwargsrD   rh   ÚCHECKED_CONVENIENCE_FUNCTIONSr    r!   ÚBinOpÚopÚsumÚleftÚrightÚadd_messageÚCallÚ_check_call_funcÚConstÚ_check_format_stringÚFormattedValueÚ	JoinedStrr?   r@   )rE   rF   r$   Z
format_posZbinopÚemitZtotal_number_of_stringsr(   )rE   r)   r_   Ö   s<    



z LoggingChecker._check_log_methodc             C   s   t | tjƒo| jdkS )zL
        Return True if the operand in argument is a literal string
        Ústr)r    r!   rs   r$   )rg   r(   r(   r)   re     s    z&LoggingChecker._is_operand_literal_strc             C   sB   t j|jƒ}d}d}t|||ƒr>t|jƒ r>| jd|| jd� dS )	z¥Checks that function call is not format_string.format().

        Args:
          node (astroid.node_classes.Call):
            Call AST node to be checked.
        rx   ÚunicodeÚformatzlogging-format-interpolation)rF   rh   N)rx   ry   )rz   )r   rf   r%   r*   Úis_complex_format_strr#   rp   r@   )rE   rF   r%   r&   r'   r(   r(   r)   rr     s    
zLoggingChecker._check_call_funcc             C   sl  t |j|d d… ƒ}|sdS |j| j}d}t|tƒr@|jƒ }t|tƒ�r6yz| jdkrttj	|ƒ\}}}}|rÄdS nP| jdkr²tj
|ƒ\}}	}
ttdd„ |D ƒƒƒ}||	 |
 }n| jd|| jd	� W nn tjk
�r } z*||j }| jd
||t|ƒ|jfd	� dS d}~X n& tjk
�r4   | jd|d� dS X ||k�rP| jd|d� n||k �rh| jd|d� dS )zêChecks that format string tokens match the supplied arguments.

        Args:
          node (astroid.node_classes.NodeNG): AST node to be checked.
          format_arg (int): Index of the format string in the node arguments.
        r;   Nr   r2   r4   c             s   s    | ]\}}t |tƒs|V  qd S )N)r    Úint)rV   ÚkÚlr(   r(   r)   rW   :  s    z6LoggingChecker._check_format_string.<locals>.<genexpr>zlogging-format-interpolation)rF   rh   zlogging-unsupported-formatzlogging-format-truncated)rF   zlogging-too-many-argszlogging-too-few-args)Ú_count_supplied_tokensrh   Úvaluer    ÚbytesÚdecoderx   r?   r   Zparse_format_stringZparse_format_method_stringrD   r<   rp   r@   ZUnsupportedFormatCharacterÚindexÚordZIncompleteFormatString)rE   rF   Z
format_argÚnum_argsÚformat_stringZrequired_num_argsZkeyword_argsÚ_Zkeyword_argumentsZimplicit_pos_argsZexplicit_pos_argsZkeyword_args_cntÚexÚcharr(   r(   r)   rt     sL    





z#LoggingChecker._check_format_stringN)r,   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ZIAstroidCheckerZ__implements__r$   ÚMSGSZmsgsÚoptionsrH   rO   rP   r   ra   r_   Ústaticmethodre   rr   rt   r(   r(   r(   r)   r+   k   s.   
$+r+   c             C   s€   t j| ƒ}|dks,t|tjƒo(t|jtƒ r0dS yttj	ƒ j
|jƒƒ}W n tk
r\   dS X x|D ]\}}}}|rddS qdW dS )zëChecks if node represents a string with complex formatting specs.

    Args:
        node (astroid.node_classes.NodeNG): AST node to check
    Returns:
        bool: True if inferred string uses complex formatting, False otherwise
    NTF)r   rf   r    r!   rs   r€   rx   ÚlistÚstringÚ	FormatterÚparseÚ
ValueError)rF   r\   Úparsedr‡   Úformat_specr(   r(   r)   r{   V  s    
r{   c             C   s   t dd„ | D ƒƒS )a|  Counts the number of tokens in an args list.

    The Python log functions allow for special keyword arguments: func,
    exc_info and extra. To handle these cases correctly, we only count
    arguments that aren't keywords.

    Args:
      args (list): AST nodes that are arguments for a log format string.

    Returns:
      int: Number of AST nodes that aren't keywords.
    c             s   s   | ]}t |tjƒsd V  qdS )r;   N)r    r!   ÚKeyword)rV   Úargr(   r(   r)   rW   {  s    z)_count_supplied_tokens.<locals>.<genexpr>)rm   )rh   r(   r(   r)   r   n  s    r   c             C   s   | j t| ƒƒ dS )z.Required method to auto-register this checker.N)Zregister_checkerr+   )Zlinterr(   r(   r)   Úregister~  s    rš   )r   r   r   )r	   r
   r   )r   r   r   )r   r   r   )r   r   r   )r   r   r   )r�   r’   r!   Zpylintr   r   Zpylint.checkersr   Zpylint.checkers.utilsr   rŽ   rj   r*   ZBaseCheckerr+   r{   r   rš   r(   r(   r(   r)   Ú<module>   sJ                l