a
    `y                     @   s   d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
mZmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ zddlZW n ey   dZY n0 dd ZG dd dZG dd dZeddZG dd deZeddZdS )z)Configuration file parsing and utilities.    N)
namedtuple)Set)NoOptionErrorNoSectionErrorRawConfigParser)reduce)compile   )__version__log)ErrorRegistryconventionsc                    s    fdd}|S )z4Check that the configuration object was initialized.c                    s2   | j d u s| jd u rtd | g|R i |S )Nz$using an uninitialized configuration)
_arguments_optionsRuntimeError)selfargskwargsmethod 0lib/python3.9/site-packages/pydocstyle/config.py
_decorator   s    z%check_initialized.<locals>._decoratorr   )r   r   r   r   r   check_initialized   s    r   c                   @   sZ   e Zd ZdZdd ZdddZddd	Zd
d Zdd ZddddZ	dd Z
dd ZdS )
TomlParsera  ConfigParser that partially mimics RawConfigParser but for toml files.

    See RawConfigParser for more info. Also, please note that not all
    RawConfigParser functionality is implemented, but only the subset that is
    currently used by pydocstyle.
    c                 C   s
   i | _ dS )zCreate a toml parser.N)_configr   r   r   r   __init__)   s    zTomlParser.__init__Nc              	   C   s   t |tttjfr|g}g }|D ]}zbt||dB}tsTtd| W d   W q | j	
t| W d   n1 sz0    Y  W n ty   Y q Y n0 t |tjrt|}|| q |S )a  Read and parse a filename or an iterable of filenames.

        Files that cannot be opened are silently ignored; this is
        designed so that you can specify an iterable of potential
        configuration file locations (e.g. current directory, user's
        home directory, systemwide directory), and all existing
        configuration files in the iterable will be read.  A single
        filename may also be given.

        Return list of successfully read files.
        )encodingzSThe %s configuration file was ignored, because the `toml` package is not installed.N)
isinstancestrbytesosPathLikeopentomlr   warningr   updateloadOSErrorfspathappend)r   	filenamesr   Zread_okfilenamefpr   r   r   read-   s&    4

zTomlParser.readFc                 C   sX   zt tj|d| jd }W n ty4   d }Y n0 t|trD|S |rLd S t|d S )N.Ztool)	r   operatorgetitemsplitr   KeyErrorr   dictr   )r   section
allow_nonecurrentr   r   r   _get_sectionN   s    

zTomlParser._get_sectionc                 C   s   | j |ddduS )zCIndicate whether the named section is present in the configuration.T)r7   N)r9   )r   r6   r   r   r   has_section_   s    zTomlParser.has_sectionc                 C   s   |  |}t| S )z9Return a list of option names for the given section name.)r9   listkeys)r   r6   r8   r   r   r   optionsc   s    
zTomlParser.options_convc                C   s   |  |}| }z|| }W n ty:   t||Y n0 t|tr\td| d| d|durt||std| d| d| |S )z(Get an option value for a given section.z	Expected r0   z  to be an option, not a section.NzThe type of z should be )r9   lowerr4   r   r   r5   	TypeError)r   r6   optionr?   dvaluer   r   r   geth   s    

zTomlParser.getc                 C   s   | j ||tdS )z/Get a boolean option value for a given section.r>   )rE   boolr   r6   rB   r   r   r   
getboolean   s    zTomlParser.getbooleanc                 C   s   | j ||tdS )z0Get an integer option value for a given section.r>   )rE   intrG   r   r   r   getint   s    zTomlParser.getint)N)F)__name__
__module____qualname____doc__r   r/   r9   r:   r=   rE   rH   rJ   r   r   r   r   r   !   s   
!
r   c                   @   s*  e Zd ZdZdZdZdZdZdZe	j
ZdZdZd	d
 Zdd Zdd Zedd Zedd Zdd Zdd Zedd Zdd Zdd Zd9ddZed d! Zed:d#d$Zed%d& Zed'd( Zed)d* Z ed+d, Z!ed-d. Z"ed/d0 Z#ed1d2 Z$ed3d4 Z%ed5d6 Z&ed7d8 Z'dS );ConfigurationParsera  Responsible for parsing configuration from files and CLI.

    There are 2 types of configurations: Run configurations and Check
    configurations.

    Run Configurations:
    ------------------
    Responsible for deciding things that are related to the user interface and
    configuration discovery, e.g. verbosity, debug options, etc.
    All run configurations default to `False` or `None` and are decided only
    by CLI.

    Check Configurations:
    --------------------
    Configurations that are related to which files and errors will be checked.
    These are configurable in 2 ways: using the CLI, and using configuration
    files.

    Configuration files are nested within the file system, meaning that the
    closer a configuration file is to a checked file, the more relevant it will
    be. For instance, imagine this directory structure:

    A
    +-- tox.ini: sets `select=D100`
    +-- B
        +-- foo.py
        +-- tox.ini: sets `add-ignore=D100`

    Then `foo.py` will not be checked for `D100`.
    The configuration build algorithm is described in `self._get_config`.

    Note: If any of `BASE_ERROR_SELECTION_OPTIONS` was selected in the CLI, all
    configuration files will be ignored and each file will be checked for
    the error codes supplied in the CLI.

    )
conventionselectignorez
add-selectz
add-ignorematchz	match-dirzignore-decorators)rR   rQ   rP   z(?!test_).*\.pyz[^\.].* )z	setup.cfgztox.iniz.pydocstylez.pydocstyle.iniz.pydocstylercz.pydocstylerc.inizpyproject.tomlz.pep257)Z
pydocstylepep257c                 C   s,   i | _ d| _d | _ | _| _|  | _dS )zCreate a configuration parser.N)_cache_override_by_clir   r   	_run_conf_create_option_parser_parserr   r   r   r   r      s    zConfigurationParser.__init__c                 C   s   |  g \}}| |S )z;Return a `RunConfiguration` object set with default values.)_parse_args_create_run_config)r   r=   _r   r   r   get_default_run_configuration   s    z1ConfigurationParser.get_default_run_configurationc                 C   sX   |   \| _| _| jpdg| _| | js0t | | j| _| j| jdd}|| _dS )zParse the configuration.

        If one of `BASE_ERROR_SELECTION_OPTIONS` was selected, overrides all
        error codes to check and disregards any error code related
        configurations from the configuration files.

        r0   F)use_defaultsN)	r[   r   r   _validate_optionsIllegalConfigurationr\   rX   _create_check_configrW   )r   configr   r   r   parse   s    zConfigurationParser.parsec                 C   s   | j S )z,Return the run configuration for the script.)rX   r   r   r   r   get_user_run_configuration   s    z.ConfigurationParser.get_user_run_configurationc                 #   s   dd }dd }| j D ]}tj|rt|D ]|\}}}| tj|}||\} ||}	 fdd|D |dd< |D ],}
||
r~tj||
}|t|j	|	fV  q~q0q| tj|}||\}}||}	||r|t|j	|	fV  qdS )a  Generate files and error codes to check on each one.

        Walk dir trees under `self._arguments` and yield file names
        that `match` under each directory that `match_dir`.
        The method locates the configuration for each file name and yields a
        tuple of (filename, [error_codes]).

        With every discovery of a new configuration file `IllegalConfiguration`
        might be raised.

        c                 S   s(   t | jd j}t | jd j}||fS )z:Return the `match` and `match_dir` functions for `config`.$)rerS   	match_dir)confZ
match_funcZmatch_dir_funcr   r   r   _get_matches  s    z<ConfigurationParser.get_files_to_check.<locals>._get_matchesc                 S   s   | j rt| j S dS )z0Return the `ignore_decorators` as None or regex.N)ignore_decoratorsrg   )ri   r   r   r   _get_ignore_decorators  s    zFConfigurationParser.get_files_to_check.<locals>._get_ignore_decoratorsc                    s   g | ]} |r|qS r   r   ).0rC   rh   r   r   
<listcomp>      z:ConfigurationParser.get_files_to_check.<locals>.<listcomp>N)
r   r"   pathisdirwalk_get_configabspathjoinr;   checked_codes)r   rj   rl   namerootdirsr,   rc   rS   rk   r-   	full_pathr]   r   rn   r   get_files_to_check   s*    
z&ConfigurationParser.get_files_to_checkc           
      C   s   |  |}|| jv r| j| S | |}|du r^tj|\}}|rP| |}q| | j}nH| 	|\}}tj|\}}|r|r| |}	| 
|	|}n
| |}|S )aw  Get a configuration for checking `node` by config discovery.

        Config discovery happens when no explicit config file is specified. The
        file system is searched for config files starting from the directory
        containing the file being checked, and up until the root directory of
        the project.

        See `_get_config` for further details.

        N)_get_node_dirrV   _get_config_file_in_folderr"   rq   r3   rt   rb   r   _read_configuration_file_merge_configuration)
r   noderq   Zconfig_fileZ
parent_dirtailrc   r=   inheritparent_configr   r   r   _get_config_by_discovery(  s     





z,ConfigurationParser._get_config_by_discoveryc           	      C   s*  | j jdu r"td | |}ntd| j j tj| j jsTtd	| j jd| j
v rh| j
d S | | j j\}}|du rtd | | j}n
| |}i }tjD ].}t| j|}t||}|dur|n|||< qtf i |}| |j| j | j jdur|| j
d< n|| j
| |< |S )a  Get and cache the run configuration for `node`.

        If no configuration exists (not local and not for the parent node),
        returns and caches a default configuration.

        The algorithm:
        -------------
        * If the current directory's configuration exists in
           `self._cache` - return it.
        * If a configuration file does not exist in this directory:
          * If the directory is not a root directory:
            * Cache its configuration as this directory's and return it.
          * Else:
            * Cache a default configuration and return it.
        * Else:
          * Read the configuration file.
          * If a parent directory exists AND the configuration file
            allows inheritance:
            * Read the parent configuration by calling this function with the
              parent directory as `node`.
            * Merge the parent configuration with the current one and
              cache it.
        * If the user has specified one of `BASE_ERROR_SELECTION_OPTIONS` in
          the CLI - return the CLI configuration with the configuration match
          clauses
        * Set the `--add-select` and `--add-ignore` CLI configurations.

        Nz&No config file specified, discovering.zUsing config file %rz=Configuration file {!r} specified via --config was not found.zVConfiguration file does not contain a pydocstyle section. Using default configuration.)rX   rc   r   debugr   r"   rq   existsra   formatrV   r   r&   rb   r   CheckConfiguration_fieldsgetattrrW   _set_add_optionsrw   r}   )	r   r   rc   r=   r]   Zfinal_configattrZcli_valZconf_valr   r   r   rt   R  s<    





zConfigurationParser._get_configc                 C   s(   t j| }t j|r|S t j|S )z?Return the absolute path of the directory of a filesystem node.)r"   rq   ru   rr   dirname)r   rq   r   r   r   r}     s    z!ConfigurationParser._get_node_dirc                 C   sx  | drt }n
tdd}d}d}||rL| |rL| jjdd }| jjD ]}||j qTdd |D }| 	g \}}	| |}
|
|
D ]}|dkr||
|}q|d	d
| jvrtd| d q|d
d	}|| }|dv r||
|}n2|dkr||
|}n|dv s(J ||
|}t||| q| |}|durp| |sptd| ||fS )zTry to read and parse `path` as a configuration file.

        If the configurations were illegal (checked with
        `self._validate_options`), raises `IllegalConfiguration`.

        Returns (options, should_inherit).

        .toml#;Zinline_comment_prefixesNTc                 S   s   i | ]}|j |jp|jqS r   )desttypeaction)rm   or   r   r   
<dictcomp>  rp   z@ConfigurationParser._read_configuration_file.<locals>.<dictcomp>r   r]   -zUnknown option 'z	' ignored)rI   countstring)
store_truestore_falsez	in file: )endswithr   r   r/   _get_section_namerZ   option_listZoption_groupsextendr[   r=   rH   replaceCONFIG_FILE_OPTIONSr   r&   rJ   rE   setattr_fix_set_optionsr`   ra   )r   rq   parserr=   Zshould_inheritZall_optionsgroupr   Znew_optionsr]   section_nameoptZnormalized_optZopt_typerD   r   r   r   r     sB    	






z,ConfigurationParser._read_configuration_filec                 C   sf   t |j}| |r | |}| || t|d}dD ]}t||pPt||||< q:tf i |S )zMerge parent config into the child options.

        The migration process requires an `options` object for the child in
        order to distinguish between mutually exclusive codes, add-select and
        add-ignore error codes.

        rw   rS   rh   rk   )	copydeepcopyrw   _has_exclusive_option_get_exclusive_error_codesr   r5   r   r   )r   r   Zchild_optionsZerror_codesr   keyr   r   r   r     s    	



z(ConfigurationParser._merge_configurationNc                 C   s    | j ||\}}| ||fS )z@Parse the options using `self._parser` and reformat the options.)rZ   
parse_argsr   )r   r   valuesr=   Z	argumentsr   r   r   r[     s    zConfigurationParser._parse_argsc                    s"    fddt jD }t f i |S )z2Create a `RunConfiguration` object from `options`.c                    s   i | ]}|t  |qS r   r   rm   r   r=   r   r   r     s   z:ConfigurationParser._create_run_config.<locals>.<dictcomp>)RunConfigurationr   )r=   r   r   r   r   r\     s    
z&ConfigurationParser._create_run_configTc                 C   st   d}|  |s|r| |}t|d}dD ]:}t||du rV|rVt| d|  dnt||||< q*tf i |S )zCreate a `CheckConfiguration` object from `options`.

        If `use_defaults`, any of the match options that are `None` will
        be replaced with their default value and the default convention will be
        set for the checked codes.

        Nr   r   ZDEFAULT_Z_RE)r   _get_checked_errorsr5   r   upperr   )clsr=   r_   rw   r   r   r   r   r   rb     s    	

z(ConfigurationParser._create_check_configc                 C   s"   | j D ]}||r|  S qdS )z$Parse options from relevant section.N)POSSIBLE_SECTION_NAMESr:   )r   r   r   r   r   r   r     s    


z%ConfigurationParser._get_section_namec                 C   sn   t j|rt j|}| jD ]J}|dr4t }n
tdd}t j||}|	|r| 
|r|  S qdS )zkLook for a configuration file in `path`.

        If exists return its full path, otherwise None.

        r   r   r   N)r"   rq   isfiler   PROJECT_CONFIG_FILESr   r   r   rv   r/   r   )r   rq   fnrc   r{   r   r   r   r~     s    


z.ConfigurationParser._get_config_file_in_folderc                 C   sh   t t }d}|jdur0| |j}|| }n.|jdurH| |j}n|jdur^tt|j}t	
|S )z;Extract the error codes from the selected exclusive option.N)setr   get_error_codesrR   _expand_error_codesrQ   rP   r   r   r   r   )r   r=   codesrw   Zignoredr   r   r   r   .  s    



z.ConfigurationParser._get_exclusive_error_codesc                 C   s$   ||  |jO }||  |j8 }dS )z@Set `checked_codes` by the `add_ignore` or `add_select` options.N)r   
add_select
add_ignore)r   rw   r=   r   r   r   r   ?  s    z$ConfigurationParser._set_add_optionsc              
      s   t t }t  }zH| D ]>     s*q fdd|D }|sLtd  || qW n. ty } zt||W Y d}~n
d}~0 0 |S )z0Return an expanded set of error codes to ignore.c                    s   h | ]}|  r|qS r   )
startswith)rm   codepartr   r   	<setcomp>S  s   z:ConfigurationParser._expand_error_codes.<locals>.<setcomp>z9Error code passed is not a prefix of any known errors: %sN)	r   r   r   stripr   r&   r'   rA   ra   )Z
code_partsr   Zexpanded_codesZcodes_to_adder   r   r   r   E  s&    
 z'ConfigurationParser._expand_error_codesc                 C   s(   |  |}|du r| j}| || |S )z6Extract the codes needed to be checked from `options`.N)r   DEFAULT_CONVENTIONr   )r   r=   rw   r   r   r   r   b  s
    
z'ConfigurationParser._get_checked_errorsc              	   C   sz   t | jdD ]4\}}t||rt||rtd||  dS q|jrv|jtvrvtd|jd	t
  dS dS )zValidate the mutually exclusive options.

        Return `True` iff only zero or one of `BASE_ERROR_SELECTION_OPTIONS`
        was selected.

           z8Cannot pass both {} and {}. They are mutually exclusive.Fz1Illegal convention '{}'. Possible conventions: {}, T)	itertoolspermutationsBASE_ERROR_SELECTION_OPTIONSr   r   errorr   rP   r   rv   r<   )r   r=   Zopt1Zopt2r   r   r   r`   m  s$    z%ConfigurationParser._validate_optionsc                    s   t  fdd| jD S )z>Return `True` iff one or more exclusive options were selected.c                    s   g | ]}t  |d uqS )Nr   r   r   r   r   ro     s   z=ConfigurationParser._has_exclusive_option.<locals>.<listcomp>)anyr   )r   r=   r   r   r   r     s
    
z)ConfigurationParser._has_exclusive_optionc                    s   d}d} fdd}|D ]&}t ||}|durt|||| q|D ]8}t ||}|du r^d}t|tsp||}t||| qD|S )z9Alter the set options from None/strings to sets in place.)rR   rQ   )r   r   c                    s.   t | tr| d}  dd | D dh S )zSplit `value_str` by the delimiter `,` and return a set.

            Removes empty values ('') and strips whitespace.
            Also expands error code prefixes, to avoid doing this for every
            file.

            ,c                 S   s   h | ]}|  qS r   )r   )rm   xr   r   r   r     rp   zIConfigurationParser._fix_set_options.<locals>._get_set.<locals>.<setcomp>rT   )r   r    r3   r   )Z	value_strr   r   r   _get_set  s
    

z6ConfigurationParser._fix_set_options.<locals>._get_setNrT   )r   r   r   r   )r   r=   Zoptional_set_optionsZmandatory_set_optionsr   r   rD   r   r   r   r     s    


z$ConfigurationParser._fix_set_optionsc              	   C   s`  ddl m}m} |tdd}|j}|ddddd	d
 |dddddd
 |dddddd
 |dddddd
 |ddddd
 |ddddd |||dd ||dd}|j}|dd dd!d |d"d dd#d |d$d%dd&d'td |d(d dd)d |d*d dd+d || |d,d-dd.| j	d |d/d-dd0| j
d |d1d2dd3| jd |S )4z<Return an option parser to parse the command line arguments.r   )OptionGroupOptionParserz+Usage: pydocstyle [options] [<file|dir>...])versionusagez-ez	--explainr   Fzshow explanation of each error)r   defaulthelpz-sz--sourcezshow source for each errorz-dz--debugzprint debug informationz-vz	--verbosezprint status informationz--countz&print total number of errors to stdoutz--configz<path>Nz2use given config file and disable config discovery)metavarr   r   ZNotezWhen using --match, --match-dir or --ignore-decorators consider whether you should use a single quote (') or a double quote ("), depending on your OS, Shell, etc.zError Check Optionsa  Only one of --select, --ignore or --convention can be specified. If none is specified, defaults to `--convention=pep257`. These three options select the "basic list" of error codes to check. If you wish to change that list (for example, if you selected a known convention but wish to ignore a specific error from it or add a new one) you can use `--add-[ignore/select]` in order to do so.z--selectz<codes>zchoose the basic list of checked errors by specifying which errors to check for (with a list of comma-separated error codes or prefixes). for example: --select=D101,D2z--ignorezchoose the basic list of checked errors by specifying which errors to ignore out of all of the available error codes (with a list of comma-separated error codes or prefixes). for example: --ignore=D101,D2z--conventionz<name>zgchoose the basic list of checked errors by specifying an existing convention. Possible conventions: {}.r   z--add-selectzpadd extra error codes to check to the basic list of errors previously set by --select, --ignore or --convention.z--add-ignorezsignore extra error codes by removing them from the basic list previously set by --select, --ignore or --convention.z--matchz	<pattern>zcheck only files that exactly match <pattern> regular expression; default is --match='{}' which matches files that don't start with 'test_' but end with '.py'z--match-dirzsearch only dirs that exactly match <pattern> regular expression; default is --match-dir='{}', which matches all dirs that don't start with a dotz--ignore-decoratorsz<decorators>zignore any functions or methods that are decorated by a function with a name fitting the <decorators> regular expression; default is --ignore-decorators='{}' which does not ignore any decorated functions.)Zoptparser   r   r
   Z
add_optionZadd_option_groupr   rv   r   DEFAULT_MATCH_REDEFAULT_MATCH_DIR_REDEFAULT_IGNORE_DECORATORS_RE)r   r   r   r   rB   Zcheck_groupZ	add_checkr   r   r   rY     s    
	
		
z)ConfigurationParser._create_option_parser)NN)T)(rK   rL   rM   rN   r   r   r   r   r   r   rU   r   r   r   r   r^   rd   r   re   r|   r   rt   staticmethodr}   r   r   r[   r\   classmethodrb   r   r~   r   r   r   r   r`   r   r   rY   r   r   r   r   rO      s^   %
	

4*G
9










	
$rO   r   )rw   rS   rh   rk   c                   @   s   e Zd ZdZdS )ra   z(An exception for illegal configurations.N)rK   rL   rM   rN   r   r   r   r   ra   e  s   ra   r   )Zexplainsourcer   verboser   rc   ) rN   r   r   r1   r"   collectionsr   collections.abcr   Zconfigparserr   r   r   	functoolsr   rg   r   Zutilsr
   r   Z
violationsr   r   r%   ImportErrorr   r   rO   r   	Exceptionra   r   r   r   r   r   <module>   s@   
g     \