U
    楡c                     @   s0  U d Z ddlZddlZddlmZ ddlZddlmZmZ ddl	Z	ddl
Z
ddlZddlZddlmZmZmZ ddlmZ ddlmZ ddlZddlmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z* e rdd	l+m,Z, dd
lm-Z- e"dddZ.e"de/e0e1e2e3Z4ej5dd dk rBddl6m7Z7 e7Z8nddlm7Z7 e7e/ee4 f Z8dZ9e	:dZ;e;<e	=  dZ>e'e?d< e@dZAG dd dejBZCede*f ede*f dddZDede*f ede*f dddZEG d d! d!ee. ZFG d"d# d#e8ZGe&e/d$d%d&ZHG d'd dejIeCd(ZJdS ))zbModule containing module parser implementation able to properly read and write
configuration files    N)wraps)BufferedReaderIOBase)defenc
force_textis_win)LockFile)AnyCallableGenericIOListDictSequenceTYPE_CHECKINGTupleTypeVarUnioncast)Lit_config_levelsConfigLevels_TupPathLikeassert_never_T)Repo)BytesIOT_ConfigParserGitConfigParser)boundT_OMD_value   )r          )OrderedDict)r   SectionConstraintz
git.config)systemuserglobal
repositoryCONFIG_LEVELSz2(?<=includeIf )\"(gitdir|gitdir/i|onbranch):(.+)\"c                       s4   e Zd ZdZeeeeef d d fddZ  Z	S )MetaParserBuilderzZUtility class wrapping base-class methods into decorators that assure read-only properties)namebasesclsdictreturnc                    s   d}||krn|| }|D ]T}dd t |t jD }|D ]2\}}||krJq8t|}	||krbt|	}	|	||< q8qtt| | |||}
|
S )z
        Equip all base-class methods with a needs_values decorator, and all non-const methods
        with a set_dirty_and_flush_changes decorator in addition to that._mutating_methods_c                 s   s    | ]}|d   ds|V  qdS )r   _N
startswith).0t r5   ./tmp/pip-unpacked-wheel-_pbxsds5/git/config.py	<genexpr>b   s      z,MetaParserBuilder.__new__.<locals>.<genexpr>)inspect
getmembers	isroutineneeds_valuesset_dirty_and_flush_changessuperr*   __new__)clsr+   r,   r-   ZkmmZmutating_methodsbasemethodsmethodZmethod_with_valuesnew_type	__class__r5   r6   r>   Z   s    zMetaParserBuilder.__new__)
__name__
__module____qualname____doc__strr   r   r	   r>   __classcell__r5   r5   rD   r6   r*   W   s   r*   .)funcr.   c                    s$   t  dtttd fdd}|S )zOReturns method assuring we read values (on demand) before we try to access themr   selfargskwargsr.   c                    s   |     | f||S N)read)rN   rO   rP   rL   r5   r6   assure_data_presentw   s    z)needs_values.<locals>.assure_data_present)r   r	   r   )rL   rT   r5   rS   r6   r;   t   s    r;   )non_const_funcr.   c                    s$   dt t td fdd} j|_|S )zReturn method that checks whether given non constant function may be called.
    If so, the instance will be set dirty.
    Additionally, we flush the changes right to diskr   rM   c                    s"    | f||}d| _ |   |S )NT)_dirtywrite)rN   rO   rP   rvalrU   r5   r6   flush_changes   s    z2set_dirty_and_flush_changes.<locals>.flush_changes)r	   r   rF   )rU   rZ   r5   rY   r6   r<      s    r<   c                       s   e Zd ZdZdZdZeeddddZddd	d
Z	ee
d fddZee
e
e
dddZeedddZddddZddddZeeeddddZ  ZS )r$   a"  Constrains a ConfigParser to only option commands which are constrained to
    always use the section we have been initialized with.

    It supports all ConfigParser methods that operate on an option.

    :note:
        If used as a context manager, will release the wrapped ConfigParser._config_section_name)	get_value	set_valuegetsetgetintgetfloat
getboolean
has_optionremove_sectionremove_optionoptionsN)configsectionr.   c                 C   s   || _ || _d S rQ   r[   )rN   ri   rj   r5   r5   r6   __init__   s    zSectionConstraint.__init__r.   c                 C   s   | j   d S rQ   r\   releaserN   r5   r5   r6   __del__   s    zSectionConstraint.__del__)attrr.   c                    s(    j kr fddS tt S )Nc                     s   j  f| |S rQ   )_call_config)rO   rP   rq   rN   r5   r6   <lambda>       z/SectionConstraint.__getattr__.<locals>.<lambda>)_valid_attrs_r=   r$   __getattribute__)rN   rq   rD   rs   r6   __getattr__   s    
zSectionConstraint.__getattr__)rB   rO   rP   r.   c                 O   s   t | j|| jf||S )zcCall the configuration at the given method which must take a section name
        as first argument)getattrr\   r]   )rN   rB   rO   rP   r5   r5   r6   rr      s    zSectionConstraint._call_configc                 C   s   | j S )z*return: Configparser instance we constrain)r\   ro   r5   r5   r6   ri      s    zSectionConstraint.configc                 C   s
   | j  S )zZEquivalent to GitConfigParser.release(), which is called on our underlying parser instancerm   ro   r5   r5   r6   rn      s    zSectionConstraint.releasez!SectionConstraint[T_ConfigParser]c                 C   s   | j   | S rQ   )r\   	__enter__ro   r5   r5   r6   rz      s    
zSectionConstraint.__enter__)exception_typeexception_value	tracebackr.   c                 C   s   | j ||| d S rQ   )r\   __exit__)rN   r{   r|   r}   r5   r5   r6   r~      s    zSectionConstraint.__exit__)rF   rG   rH   rI   	__slots__rv   r   rJ   rk   rp   r	   rx   rr   propertyri   rn   rz   r~   rK   r5   r5   rD   r6   r$      s   r$   c                       s  e Zd ZdZeedd fddZeedd fddZee	e dd fd	d
Z
eed fddZeed fddZeedd fddZdeeedf eedf d fddZee	e d fddZe	eeef  dddZe	eee	e f  dddZ  ZS )_OMDzOrdered multi-dict.N)keyvaluer.   c                    s   t t| ||g d S rQ   r=   r   __setitem__rN   r   r   rD   r5   r6   r      s    z_OMD.__setitem__c                    s:   || kr t t| ||g d S t t| || d S rQ   )r=   r   r   __getitem__appendr   rD   r5   r6   add   s    z_OMD.add)r   valuesr.   c                    s   t t| || d S rQ   r   )rN   r   r   rD   r5   r6   setall   s    z_OMD.setall)r   r.   c                    s   t t| |d S Nr=   r   r   rN   r   rD   r5   r6   r      s    z_OMD.__getitem__c                    s   t t| |d S r   r   r   rD   r5   r6   getlast   s    z_OMD.getlastc                    s<   || kr t t| ||g d S t t| |}||d< d S r   )r=   r   r   r   )rN   r   r   ZpriorrD   r5   r6   setlast   s
    z_OMD.setlast)r   defaultr.   c                    s   t t| ||gd S r   )r=   r   r`   )rN   r   r   rD   r5   r6   r`      s    z_OMD.getc                    s   t t| |S rQ   r   r   rD   r5   r6   getall   s    z_OMD.getallrl   c                    s    fdd D S )z"List of (key, last value for key).c                    s   g | ]}| | fqS r5   r5   r3   kro   r5   r6   
<listcomp>   s     z_OMD.items.<locals>.<listcomp>r5   ro   r5   ro   r6   items   s    z
_OMD.itemsc                    s    fdd D S )z&List of (key, list of values for key).c                    s   g | ]}|  |fqS r5   )r   r   ro   r5   r6   r      s     z"_OMD.items_all.<locals>.<listcomp>r5   ro   r5   ro   r6   	items_all   s    z_OMD.items_all)N)rF   rG   rH   rI   rJ   r   r   r	   r   r   r   r   r   r   r   r`   r   r   r   r   rK   r5   r5   rD   r6   r      s   (r   )config_levelr.   c              	   C   s   t r| dkrd} | dkrdS | dkr`tjdpDttjddd}ttt|d	d
S | dkrxttdS | dkrtdnt	| td|  d S )Nr%   r'   z/etc/gitconfigr&   XDG_CONFIG_HOMEHOME~z.configgitri   z~/.gitconfigr(   zGNo repo to get repository configuration from. Use Repo._get_config_pathzInvalid configuration level: )
r   osenvironr`   ospjoinnormpath
expanduser
ValueErrorr   )r   Zconfig_homer5   r5   r6   get_config_path   s    "
r   c                
       s  e Zd ZdZeZedZdZ	ee	Z
ee	d d Z[	dZdKeded	eeed	f  f eeeedf ed
 ddddZddddZddddZd dddZeddddZddddZeedddZeeee f eddddZeeef dd d!Z e!e"eef  dd"d#Z#ddd$d%Z$edd&d'd(Z%ee!e"eef  d) fd*d+Z&ee!e"ee!e f  d)d,d-Z'e(ddd.d/Z)edd0d1d2Z*edd3 fd4d5Z+e,edd6d7Z-dLeeeee.eedf eee.eef d8d9d:Z/dMeeeee.eedf e!eee.eef  d8d;d<Z0eeee.eef d=d>d?Z1eeeee.ef ed@dAdBZ2e(e3eeeeeee.ef d dCdDdEZ4e(e3eeeeeee.ef d dCdFdGZ5eed dH fdIdJZ6  Z7S )Nr   a  Implements specifics required to read git style configuration files.

    This variation behaves much like the git.config command such that the configuration
    will be read on demand based on the filepath given during initialization.

    The changes will automatically be written once the instance goes out of scope, but
    can be triggered manually as well.

    The configuration file will be locked if you intend to change values preventing other
    instances to write concurrently.

    :note:
        The config is case-sensitive even when queried, hence section and option names
        must match perfectly.
        If used as a context manager, will release the locked file.z^\s*[#;]z\s*(?P<option>[^:=\s][^:=]*)z\s*(?P<vi>[:=])\s*z(?P<value>.*)$)add_sectionrf   rg   ra   NTr   )r   N)file_or_files	read_onlymerge_includesr   repor.   c                 C   s   t jj| td |  |  |  t| ds0|  | _|dk	r@|| _n4|dkrh|r^dd tD | _qtt	dnt
|g| _|| _d| _d| _|| _|| _d| _|   dS )a;  Initialize a configuration reader to read the given file_or_files and to
        possibly allow changes to it by setting read_only False

        :param file_or_files:
            A single file path or file objects or multiple of these

        :param read_only:
            If True, the ConfigParser may only read the data , but not change it.
            If False, only a single file path or file object may be given. We will write back the changes
            when they happen, or when the ConfigParser is released. This will not happen if other
            configuration files have been included
        :param merge_includes: if True, we will read files mentioned in [include] sections and merge their
            contents into ours. This makes it impossible to write back an individual configuration file.
            Thus, if you want to modify a single configuration file, turn this off to leave the original
            dataset unaltered when reading it.
        :param repo: Reference to repository to use if [includeIf] sections are found in configuration files.

        )	dict_type_proxiesNc                 S   s"   g | ]}|d krt tt|qS )r(   )r   r   r   )r3   fr5   r5   r6   r   `  s     z,GitConfigParser.__init__.<locals>.<listcomp>z7No configuration level or configuration files specifiedF)cpRawConfigParserrk   r   hasattr_dictr   _file_or_filesr)   r   r   
_read_onlyrV   _is_initialized_merge_includes_repo_lock_acquire_lock)rN   r   r   r   r   r   r5   r5   r6   rk   8  s,    



zGitConfigParser.__init__rl   c                 C   sd   | j s`| jsVt| jttjfr&| j}n$t| jttt	frBt
dn| jj}| || _| j  d S )NzVWrite-ConfigParsers can operate on a single file only, multiple files have been passed)r   r   
isinstancer   rJ   r   r   tuplelistr   r   r+   t_lock_obtain_lock)rN   r   r5   r5   r6   r   p  s    zGitConfigParser._acquire_lockc                 C   s   |    dS )z3Write pending changes if required and release locksNrn   ro   r5   r5   r6   rp     s    zGitConfigParser.__del__c                 C   s   |    | S rQ   )r   ro   r5   r5   r6   rz     s    zGitConfigParser.__enter__)rO   r.   c                 G   s   |    d S rQ   r   )rN   rO   r5   r5   r6   r~     s    zGitConfigParser.__exit__c                 C   s|   | j s| jr| j sdS zFz|   W n4 tk
rJ   tjddd Y n tk
r\   Y nX W 5 | jdk	rv| j  X dS )zFlush changes and release the configuration write lock. This instance must not be used anymore afterwards.
        In Python 3, it's required to explicitly release locks and flush changes, as __del__ is not called
        deterministically anymore.Nz/Exception during destruction of GitConfigParserT)exc_info)	r   r   Z	_has_lockZ_release_lockrW   IOErrorlogerrorReferenceErrorro   r5   r5   r6   rn     s    

zGitConfigParser.release)	optionstrr.   c                 C   s   |S )z0Do not transform options in any way when writingr5   )rN   r   r5   r5   r6   optionxform  s    zGitConfigParser.optionxform)fpfpnamer.   c                 C   s  d}d}d}d}d}t t ddd}| t}	|	s:qz|d }|	 dks$| j|	r\q$|	ddd  d	kr|	d d
krq$| j	|	 }
|s|
r|

d }|| jkr| j| }n6|tjkr| j}n$| d|ff}|| j|< d| j|< d}q$|dkrt|||	q$|s6| j|	}
|
r|

ddd\}}}|dkrd|kr| ds|d}|dkr||d   r|d| }| }|dkrd}| | }t|dkr|d dkr|d dkrd}||dd }||| n.| j|	s$|s"t|}||t|	 q$q$|	 }	|	drZd}|	dd }	||}| ||||	  q$|r|dS )a  A direct copy of the py2.4 version of the super class's _read method
        to assure it uses ordered dicts. Had to change one line to make it work.

        Future versions have this fixed, but in fact its quite embarrassing for the
        guys not to have done it right in the first place !

        Removed big comments to make it more compact.

        Made sure it ignores initial whitespace as git uses tabsNr   F)vr.   c                 S   s(   | d dkr| d d } |  tdS )Nr   \Zunicode_escape)encoder   decode)r   r5   r5   r6   string_decode  s    z,GitConfigParser._read.<locals>.string_decode    remZrRheaderrF   optionvir   )=:;"r   z""T)!rJ   readliner   r   strip
re_commentmatchsplitlowerSECTCREgroup	_sectionsr   DEFAULTSECT	_defaultsr   r   MissingSectionHeaderErrorOPTCREr2   findisspacer   rstriplenr   OPTVALUEONLYParsingErrorr   reprendswithr   r   )rN   r   r   cursectoptnamelinenoZis_multi_lineer   linemosectnamer   optvalposr5   r5   r6   _read  sp    
$




$

*

zGitConfigParser._readc                 C   s   | j ot|  S rQ   )r   r   _included_pathsro   r5   r5   r6   _has_includes  s    zGitConfigParser._has_includesc              	      s:  g }|   D ]&}|dkr(|| |7 }t|}|dks| jdkrFq|d}|d  |dkrt  t	 fdddD sd	    
d
r d7  |
drtddd   | jjrtt| jj r|| |7 }q|dkrz| jjj}W n tk
r   Y qY nX t| r|| |7 }q|S )zkReturn List all paths that must be included to configuration
        as Tuples of (option, value).
        includeNr   r"   )Zgitdirzgitdir/ic                 3   s   | ]}  |V  qd S rQ   r1   )r3   sr   r5   r6   r7   %  s     z2GitConfigParser._included_paths.<locals>.<genexpr>)z.//z**/r   z**z/iz[a-zA-Z]c                 S   s   d |   |   S )Nz[{}{}])formatr   r   upper)mr5   r5   r6   rt   .  ru   z1GitConfigParser._included_paths.<locals>.<lambda>Zonbranch)sectionsr   CONDITIONAL_INCLUDE_REGEXPsearchr   r   r   r   r   anyr   resubgit_dirfnmatchfnmatchcaserJ   Zactive_branchr+   	TypeError)rN   pathsrj   r   keywordbranch_namer5   r   r6   r     s@    





zGitConfigParser._included_pathsc           	   	   C   s  | j r
dS d| _ dg}t| jttjfr2| jg}n&t| jtttfsN| jg}n
t| j}t	|}d}|r|
d}d}t|drttt |}| ||j nPtt|}z,t|d}d}| ||j W 5 Q R X W n tk
r   Y qdY nX |  rd|  D ]\}}|drt|}t|sd|s4q tt|}t|sRtd	tt||}t|}||ks t|tjsq || | d| |d
7 }q qd|dkrd| _!dS )zReads the data stored in the files we have been initialized with. It will
        ignore files that cannot be read, possibly leaving an empty configuration

        :return: Nothing
        :raise IOError: if a file cannot be handledNTr   r   Fseekrbr   z9Need absolute paths to be sure our cycle checks will workr   )"r   r   r   rJ   r   r   r   r   r   ra   popr   r   r   bytesr   r+   openr   r   r   r2   r   r   isabsAssertionErrorr   dirnamer   accessR_OKr   insertr   )	rN   Zfiles_to_readseenZnum_read_include_files	file_pathZfile_okr   r0   Zinclude_pathr5   r5   r6   rR   A  sT    











zGitConfigParser.read)r   r.   c                    sN   t tdd fdd}jr,|tjj j D ]\}}||| q6dS )z_Write an .ini-format representation of the configuration state in
        git compatible formatN)r+   section_dictr.   c              
      sd     d|  t | D ]B\}}|dkr.q|D ]*}  d||ddf t q2qd S )Nz[%s]
rF   z		%s = %s

z
	)rW   r   r   r   _value_to_stringreplace)r+   r  r   r   r   r   rN   r5   r6   write_section  s    z-GitConfigParser._write.<locals>.write_section)rJ   r   r   r   r   r   r   )rN   r   r  r+   r   r5   r  r6   _write  s
    zGitConfigParser._write)section_namer.   c                    s   dd t t| |D S )zK:return: list((option, value), ...) pairs of all items in the given sectionc                 S   s    g | ]\}}|d kr||fqS )rF   r5   )r3   r   r   r5   r5   r6   r     s      z)GitConfigParser.items.<locals>.<listcomp>)r=   r   r   )rN   r   rD   r5   r6   r     s    zGitConfigParser.itemsc                 C   sb   t | j}| j|  D ]@\}}|dkr*q||krB|||krBq|D ]}||| qFq| S )zQ:return: list((option, [values...]), ...) pairs of all items in the given sectionrF   )r   r   r   r   r   r   )rN   r   rvr   vsr   r5   r5   r6   r     s    
zGitConfigParser.items_allc              	   C   s   |  d | jsdS t| jttfr6tdt| j |  rLt	
d dS | j}t|ttjtf}|r|| jdk	r|| j  t|dstt|}t|d}| | W 5 Q R X n0td|}|d t|d	r|  | | dS )
zWrite changes to our file, if there are changes at all

        :raise IOError: if this is a read-only writer instance or if we could not obtain
            a file lockrW   NzRCannot write back if there is not exactly a single file to write to, have %i fileszsSkipping write-back of configuration file as include files were merged in.Set merge_includes=False to prevent this.r  wbr   r   truncate)_assure_writablerV   r   r   r   r   r  r   r   r   debugrJ   r   r   r   r   r   r   r   r  r  r  r$  )rN   r   Zis_file_lockZfp_openr5   r5   r6   rW     s6    






zGitConfigParser.write)method_namer.   c                 C   s   | j rtd| |f d S )Nz(Cannot execute non-constant method %s.%s)r   r   )rN   r'  r5   r5   r6   r%    s    z GitConfigParser._assure_writable)rj   r.   c                    s   t t| |S )z(Assures added options will stay in order)r=   r   r   )rN   rj   rD   r5   r6   r     s    zGitConfigParser.add_sectionc                 C   s   | j S )z@:return: True if this instance may change the configuration file)r   ro   r5   r5   r6   r     s    zGitConfigParser.read_only)rj   r   r   r.   c                 C   sB   z|  ||}W n& tk
r6   |dk	r0| Y S  Y nX | |S )a  Get an option's value.

        If multiple values are specified for this option in the section, the
        last one specified is returned.

        :param default:
            If not None, the given default value will be returned in case
            the option did not exist
        :return: a properly typed value, either int, float or string

        :raise TypeError: in case the value could not be understood
            Otherwise the exceptions known to the ConfigParser will be raised.N)r`   	Exception_string_to_value)rN   rj   r   r   valuestrr5   r5   r6   r^     s    zGitConfigParser.get_valuec                    sP   z j | |}W n( tk
r<   |dk	r6|g Y S  Y nX  fdd|D S )a  Get an option's values.

        If multiple values are specified for this option in the section, all are
        returned.

        :param default:
            If not None, a list containing the given default value will be
            returned in case the option did not exist
        :return: a list of properly typed values, either int, float or string

        :raise TypeError: in case the value could not be understood
            Otherwise the exceptions known to the ConfigParser will be raised.Nc                    s   g | ]}  |qS r5   )r)  )r3   r*  ro   r5   r6   r   %  s     z.GitConfigParser.get_values.<locals>.<listcomp>)r   r   r(  )rN   rj   r   r   lstr5   ro   r6   
get_values  s    
zGitConfigParser.get_values)r*  r.   c              
   C   s   t tf}|D ]D}z"||}|t|kr*W q|W   S  ttfk
rN   Y qY qX q| }|dkrfdS |dkrrdS t|tstd||S )NfalseFtrueTz=Invalid value type: only int, long, float and str are allowed)intfloatr   r  r   r   rJ   )rN   r*  typesZnumtypevalZvlr5   r5   r6   r)  '  s(    

z GitConfigParser._string_to_value)r   r.   c                 C   s    t |tttfrt|S t|S rQ   )r   r/  r0  boolrJ   r   )rN   r   r5   r5   r6   r  C  s    z GitConfigParser._value_to_string)rj   r   r   r.   c                 C   s,   |  |s| | | ||| | | S )a  Sets the given option in section to the given value.
        It will create the section if required, and will not throw as opposed to the default
        ConfigParser 'set' method.

        :param section: Name of the section in which the option resides or should reside
        :param option: Name of the options whose value to set

        :param value: Value to set the option to. It must be a string or convertible
            to a string
        :return: this instance)has_sectionr   ra   r  rN   rj   r   r   r5   r5   r6   r_   H  s    

zGitConfigParser.set_valuec                 C   s0   |  |s| | | j| || | | S )aI  Adds a value for the given option in section.
        It will create the section if required, and will not throw as opposed to the default
        ConfigParser 'set' method. The value becomes the new value of the option as returned
        by 'get_value', and appends to the list of values returned by 'get_values`'.

        :param section: Name of the section in which the option resides or should reside
        :param option: Name of the option

        :param value: Value to add to option. It must be a string or convertible
            to a string
        :return: this instance)r4  r   r   r   r  r5  r5   r5   r6   	add_valueZ  s    

zGitConfigParser.add_value)rj   new_namer.   c                    st   |  |std| |  |r,td| tt| | | j| }| |D ]\}}||| qP| | | S )zrename the given section to new_name
        :raise ValueError: if section doesn't exit
        :raise ValueError: if a section with new_name does already exist
        :return: this instance
        z!Source section '%s' doesn't existz'Destination section '%s' already exists)	r4  r   r=   r   r   r   r   r   rf   )rN   rj   r7  Znew_sectionr   r"  rD   r5   r6   rename_sectionm  s    



zGitConfigParser.rename_section)NTTNN)N)N)8rF   rG   rH   rI   r   r   r  compiler   Zoptvalueonly_sourcer   r   r/   r   r   r   r3  r   rk   r   rp   rz   r	   r~   rn   rJ   r   r   r   r  r   r/  r   r   r   r   rR   r  r   r   r;   rW   r%  r   r   r   r0  r^   r,  r)  r  r<   r_   r6  r8  rK   r5   r5   rD   r6   r     s~   

     
8c0H  +   &&)	metaclass)KrI   sysabc	functoolsr   r8   ior   r   loggingr   r  r  Z
git.compatr   r   r   Zgit.utilr   os.pathpathr   configparserr   typingr	   r
   r   r   r   r   r   r   r   r   r   r   Z	git.typesr   r   r   r   r   Zgit.repo.baser   r   r   rJ   r  r/  r0  r3  r   version_infocollectionsr#   ZOrderedDict_OMD__all__	getLoggerr   
addHandlerNullHandlerr)   __annotations__r9  r   ABCMetar*   r;   r<   r$   r   r   r   r   r5   r5   r5   r6   <module>   sJ   8

  >,