a
    g	gZ                  :   @   s~  d dl Z d dlZd dl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 d dlmZ d dlmZ d dlm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mZ d dl Z d d	l!m"Z" d d
l#m$Z$ d dl%m&Z& d dl'm(Z( d dl)m*Z+ d dl,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ d dlAmBZBmCZCmDZDmEZEmFZFmGZGmHZH d dlImJZJmKZKmLZL d dlMmNZNmOZO d dlPmQZQmRZRmSZSmTZTmUZUmVZV d dlWmXZXmYZYmZZZm[Z[m\Z\ d dl]m^Z^m_Z_m`Z`maZambZbmcZc d dldmeZe d dldmfZfmgZgmhZh d dlimjZjmkZkmlZl d dlmmnZn d dlompZp d dlqmrZrmsZs eetjudv ZvewZxewZyewZzG dd  d eZ{eTZ|e j}e j~eew eew d!d"d#Ze j}ee je j~f eewd$f eeU d%d&d'Zeweew d(d)d*Ze j}e j~eew eeew  d!d+d,Ze jd-d.d/gid0d1e jd2d3ewd4d5e jd6d7ee6d8d9d:e jd;d<e d=d> eUD ed9d?d@e jdAd9dBdCe jdDd9dEdCe jdFd9dGdHeeB dIg dJe jdKdLd9dMdCe jdNdOd9dPdCe jdQdRd9dSdCe jdTd9d9dUdVe jdWd9dXdCe jdYd9dZdCe jd[d9d\dCe jd]d9d^dCe jd_d9d`dCe jdaewdbd5e jdcewe5eddd9dee jdfewedge4 dhdidje jdkewedldme jdnewedodme jdpewdqd5e jdrdse jdtduddvdwe jdxdyd9dzdCe jd{d|d9d}dCe je+d~evrdnd de  de  de jdde jd9d9d9d9d9dd9dde jde jd9d9did9diewdd9edde je j}eew eeeU eeeeeeeew eeeeeeeeew eew eeew  eeew  eeew  eew ee eewd$f eew ddddZe j}eewd$f eeeew eeew  eeew  eeew  deew ee dddZeeweee j}ddddZewee{eTelddddZe$d9deee{eTdddddZe{jdfeeeTe{eedddZde{jdeeew e{eTedddZeweweTddddZeweeTexdddZeweTddddZeweeTewdddZeewef ddddZeweeTexdddZeweTewdddZeweTewdddZeeexeyezf dddZddeseeew  eeS dddZddeseeew  eeU dddÄZeseew dĜddƄZewewddǜddɄZeweweTddʜdd̄Zeed d͜ddτZdd͜ddфZdd͜ddӄZedkrze  dS )    N)contextmanager)replace)datetime)Enum)JSONDecodeError)Path)AnyDict	GeneratorIteratorListMutableMappingOptionalPatternSequenceSetSizedTupleUnion)ParameterSource)
mypyc_attr)PathSpec)GitWildMatchPatternError)version)Cacheget_cache_info
read_cachewrite_cache)normalize_fmt_off)DEFAULT_EXCLUDESDEFAULT_INCLUDESDEFAULT_LINE_LENGTHSTDIN_PLACEHOLDER)find_project_rootfind_pyproject_tomlfind_user_pyproject_tomlgen_python_filesget_gitignorenormalize_path_maybe_ignoreparse_pyproject_tomlwrap_stream_for_windows)PYTHON_CELL_MAGICSTRANSFORMED_MAGICS"jupyter_dependencies_are_installed	mask_cellput_trailing_semicolon_backremove_trailing_semicolonunmask_cell)LNLineGeneratortransform_line)EmptyLineTracker
LinesBlock)FUTURE_FLAG_TO_FEATUREVERSION_TO_FEATURESFeatureModeTargetVersionsupports_feature)STARSis_number_tokenis_simple_decorator_expressionis_string_tokensyms)
color_diffdiffdump_to_fileerr
ipynb_diffout)InvalidInput)lib2to3_parse	parse_aststringify_ast)ChangedNothingChangedReport)iter_fexpr_spans)token)LeafNode)z.pydz.soc                   @   s>   e Zd ZdZdZdZdZdZedde	e	e	d dd	d
Z
dS )	WriteBackr               F)color)checkrC   rX   returnc                C   s,   |r|s| j S |r|r| jS |r&| jS | jS N)CHECK
COLOR_DIFFDIFFYES)clsrY   rC   rX    ra   Q/var/www/html/llm_bihealth/app/venv/lib/python3.9/site-packages/black/__init__.pyfrom_configurationh   s
    zWriteBack.from_configurationN)__name__
__module____qualname__NOr_   r^   r\   r]   classmethodboolrc   ra   ra   ra   rb   rS   a   s   rS   )ctxparamvaluerZ   c              
   C   s   |s"t | jdd}|du r"dS zt|}W n> ttfyl } z"tj|d| ddW Y d}~n
d}~0 0 |svdS dd | D }|d}|durt	|t
std	d
i }| jr|| j || || _|S )zInject Black configuration from "pyproject.toml" into defaults in `ctx`.

    Returns the path to a successfully found and read configuration file, None
    otherwise.
    srcra   Nz"Error reading configuration file: )filenamehintc                 S   s,   i | ]$\}}|t |ttfs$t|n|qS ra   )
isinstancelistdictstr).0kvra   ra   rb   
<dictcomp>   s   z'read_pyproject_toml.<locals>.<dictcomp>target_versionztarget-versionz(Config key target-version must be a list)r$   paramsgetr)   OSError
ValueErrorclickZ	FileErroritemsrp   rq   ZBadOptionUsagedefault_mapupdate)rj   rk   rl   configerx   r   ra   ra   rb   read_pyproject_tomly   s8    


r   .)cprv   rZ   c                 C   s   dd |D S )zCompute the target versions from a --target-version flag.

    This is its own function because mypy couldn't infer the type correctly
    when it was a lambda, causing mypyc trouble.
    c                 S   s   g | ]}t |  qS ra   )r;   upper)rt   valra   ra   rb   
<listcomp>       z2target_version_option_callback.<locals>.<listcomp>ra   )r   r   rv   ra   ra   rb   target_version_option_callback   s    r   )regexrZ   c                 C   s   d| v rd|  } t | }|S )zdCompile a regular expression string in `regex`.

    If it contains newlines, use verbose mode.
    
z(?x))recompile)r   Zcompiledra   ra   rb   re_compile_maybe_verbose   s    
r   c              
   C   sT   z|d urt |nd W S  tjyN } ztd| d W Y d }~n
d }~0 0 d S )Nz Not a valid regular expression: )r   r   errorr}   ZBadParameter)rj   rk   rl   r   ra   ra   rb   validate_regex   s    r   Zhelp_option_namesz-hz--help"The uncompromising code formatter.)Zcontext_settingshelpz-cz--codez&Format the code passed in as a string.)typer   z-lz--line-lengthz&How many characters per line to allow.T)r   defaultr   show_defaultz-tz--target-versionc                 C   s   g | ]}|j  qS ra   )namelower)rt   rv   ra   ra   rb   r      r   r   zPython versions that should be supported by Black's output. By default, Black will try to infer this from the project metadata in pyproject.toml. If this does not yield conclusive results, Black will use per-file auto-detection.)r   callbackmultipler   z--pyiztFormat all input files like typing stubs regardless of file extension (useful when piping source on standard input).)is_flagr   z--ipynbzyFormat all input files like Jupyter Notebooks regardless of file extension (useful when piping source on standard input).z--python-cell-magicsz[When processing Jupyter Notebooks, add the given magic to the list of known python-magics (, z9). Useful for formatting cells with custom python magics.)r   r   r   z-xz--skip-source-first-linez'Skip the first line of the source code.z-Sz--skip-string-normalizationz*Don't normalize string quotes or prefixes.z-Cz--skip-magic-trailing-commaz5Don't use trailing commas as a reason to split lines.z --experimental-string-processingzE(DEPRECATED and now included in --preview) Normalize string literals.)r   hiddenr   z	--previewzvEnable potentially disruptive style changes that may be added to Black's main functionality in the next major release.z--checkzDon't write the files back, just return the status. Return code 0 means nothing would change. Return code 1 means some files would be reformatted. Return code 123 means there was an internal error.z--diffzGDon't write the files back, just output a diff for each file on stdout.z--color/--no-colorz7Show colored diff. Only applies when `--diff` is given.z--fast/--safez@If --fast given, skip temporary sanity checks. [default: --safe]z--required-versionzRequire a specific version of Black to be running (useful for unifying results across many environments e.g. with a pyproject.toml file). It can be either a major version number or an exact version.z	--includea"  A regular expression that matches files and directories that should be included on recursive searches. An empty value means all files are included regardless of the name. Use forward slashes for directories on all platforms (Windows, too). Exclusions are calculated first, inclusions later.)r   r   r   r   r   z	--excludea  A regular expression that matches files and directories that should be excluded on recursive searches. An empty value means no paths are excluded. Use forward slashes for directories on all platforms (Windows, too). Exclusions are calculated first, inclusions later. [default: ]F)r   r   r   r   z--extend-excludezLike --exclude, but adds additional files and directories on top of the excluded ones. (Useful if you simply want to add to the default))r   r   r   z--force-excludezLike --exclude, but files and directories matching this regex will be excluded even when they are passed explicitly as arguments.z--stdin-filenamezThe name of the file when passing it through stdin. Useful to make sure Black will respect --force-exclude option on some editors that rely on using stdin.z-Wz	--workersrT   )minzBNumber of parallel workers [default: number of CPUs in the system])r   r   r   z-qz--quietzbDon't emit non-error messages to stderr. Errors are still emitted; silence those with 2>/dev/null.z-vz	--verboseziAlso emit messages to stderr about files that were not changed or were ignored due to exclusion patterns.z!%(prog)s, %(version)s (compiled: yesnoz
)
Python (z) )r   messagerm   )exists	file_okaydir_okayreadable
allow_dashzSRC ...)nargsr   is_eagermetavarz--config)r   r   r   r   r   	path_typez"Read configuration from FILE path.)r   r   r   r   )rj   codeline_lengthrx   rY   rC   rX   fastpyiipynbpython_cell_magicsskip_source_first_lineskip_string_normalizationskip_magic_trailing_commaexperimental_string_processingpreviewquietverboserequired_versionincludeexcludeextend_excludeforce_excludestdin_filenameworkersrm   r   rZ   c           )         sp  |  t |r2|dur2tt| d  | d |sZ|du rZtt| d  | d |du rlt||nd\ } | jd< |rx rtd  d| d	d
d  fdd|D }ddd |D }td| d
d |rx| 	d}t
t }||krtd| dd
d n4|tjtjfv r4tdd
d ntd| dd
d | jrx| j D ]\} }!t|  d|!  qZd}"|r|tkr|td	d krt|" d| dt d | d |	r|rtd | d tj|||d}#|rt|}$nt }$t|$|||	|| | ||t|
d
}%|dur:d}t||||d }&|durht|||#|%|&d! nz t| ||||||||&|d"
}'W n ty   | d Y n0 t|'d#|||  t|'dkrt|' ||#|%|&d$ n dd%l m!}( |(|'||#|%|&|d& |s
|s`|du r0|s*|&j"s*|&j#r0t  t|&j$r>|"nd' |du r`t%j&t
|&dd( | |&j$ dS ))r   Nz3

'SRC' and 'code' cannot be passed simultaneously.rT   z%

One of 'SRC' or 'code' is required.)NNrootzIdentified `z` as project root containing a .Zblue)Zfgc                    s.   g | ]&}|d kr||fnt t| |fqS )-)r(   r   )rt   sourcer   ra   rb   r     s   
zmain.<locals>.<listcomp>r   c                 S   s,   g | ]$\}}|rd | d n
d| dqS )"z[31m"z (skipping - invalid)"[34mra   )rt   Z_normr   ra   ra   rb   r     s   zSources to be formatted: r   z/Using configuration from user-level config at 'z'.z&Using configuration from project root.zUsing configuration in 'z: u   Oh no! 💥 💔 💥r   z The required version `z&` does not match the running version `z`!z)Cannot pass both `pyi` and `ipynb` flags!)rY   rC   rX   )
target_versionsr   is_pyiis_ipynbr   Zstring_normalizationZmagic_trailing_commar   r   r   T)rY   rC   r   r   )contentr   
write_backmodereport)
rj   rm   r   r   r   r   r   r   r   r   u?   No Python files are present to be formatted. Nothing to do 😴)rm   r   r   r   r   )reformat_many)sourcesr   r   r   r   r   u   All done! ✨ 🍰 ✨)rE   )'Zensure_objectrr   rG   main	get_usageexitr#   objjoinZget_parameter_sourcers   r%   r   DEFAULTZDEFAULT_MAPr   r~   __version__splitrE   rS   rc   setr:   rN   reformat_codeget_sourcesr   
path_emptylenreformat_onepopZblack.concurrencyr   Zchange_countZfailure_countZreturn_coder}   Zecho))rj   r   r   rx   rY   rC   rX   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rm   r   method
normalizedZsrcs_stringZconfig_sourceZuser_level_configrk   rl   	error_msgr   versionsr   r   r   r   ra   r   rb   r      s     















	 
r   rN   )rj   rm   r   r   r   r   r   r   r   r   rZ   c        
         C   s  t  }
| jd }|du }|du r(ttn|}d}t|}|D ]P}|dkr\|	r\t|	}d}nt|}d}|sv| rt|| jd |}|du rq<d| }|r||}nd}|r|	dr|
|d q<|rtt t| }|jd	krt||d
sq<|
| q<| rj|t|| jd | }|r<|||t|i}|
t| | jd ||||||||d

 q<|dkr|
| q<td|  q<|
S )z)Compute the set of files to be formatted.r   Nr   TF/r   z.matches the --force-exclude regular expression.ipynb)r   r   zinvalid path: )r   r   r   r   r'   r   is_filer(   searchgroupZpath_ignoredr"   rs   suffixr-   addis_dirr   r&   iterdirrE   )rj   rm   r   r   r   r   r   r   r   r   r   r   Zusing_default_excludeZ	gitignoreZroot_gitignoresr   is_stdinZnormalized_pathZforce_exclude_matchra   ra   rb   r   n  sl    



r   )rm   msgr   r   rj   rZ   c                 C   s"   | s|s|st | |d dS )z;
    Exit if there is no `src` provided for formatting
    r   N)rG   r   )rm   r   r   r   rj   ra   ra   rb   r     s    r   )r   r   r   r   r   rZ   c              
   C   s|   t d}z,tj}t| |||dr&tj}||| W nB tyv } z*|jrRt	  |
|t| W Y d}~n
d}~0 0 dS )a  
    Reformat and print out `content` without spawning child processes.
    Similar to `reformat_one`, but for string content.

    `fast`, `write_back`, and `mode` options are passed to
    :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
    z<string>)r   r   r   r   N)r   rL   rg   format_stdin_to_stdoutr_   done	Exceptionr   	traceback	print_excfailedrs   )r   r   r   r   r   pathchangedexcra   ra   rb   r     s    
r   )Z	patchable)rm   r   r   r   r   rZ   c              
   C   s  zHt j}t| dkrd}n0t| trHd}tt| ttd } nd}|r| jdkrht|dd}n| jdkr~t|dd}t	|||d	rt j
}ni }|tjtjfvrt|}|  }t|}	|	|v r||	 t|krt j}|t jurt| |||d	rt j
}|tj
u r|t jus.|tju r<|t ju r<t|| g| || | W nF ty }
 z,|jrlt  || t|
 W Y d}
~
n
d}
~
0 0 dS )
zReformat a single file under `src` without spawning child processes.

    `fast`, `write_back`, and `mode` options are passed to
    :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
    r   TNF.pyir   r   r   )r   r   r   )rL   rg   rs   
startswithr"   r   r   r   r   r   r_   rS   r^   r]   r   resolver   ZCACHEDformat_file_in_placer\   r   r   r   r   r   r   r   )rm   r   r   r   r   r   r   cacheZres_srcZ	res_src_sr   ra   ra   rb   r     sJ    	

r   )rm   r   r   r   lockrZ   c                 C   s  | j dkrt|dd}n| j dkr.t|dd}t|  j}d}t| d0}|jr\| }t	|
 \}}	}
W d   n1 s0    Y  zt|||d	}W n6 ty   Y d
S  ty   td|  ddY n0 ||	| }||	| }|tjkr<t| d|	|
d}|| W d   n1 s00    Y  n|tjtjfv rt }|  d| d}|  d| d}|jrt||||}nt||||}|tjkrt|}|pt @ tjtjj|	|
dd}t |}|| |!  W d   n1 s0    Y  dS )zFormat file under `src` path. Return True if changed.

    If `write_back` is DIFF, write a diff to stdout. If it is YES, write reformatted
    code to the file.
    `mode` and `fast` options are passed to :func:`format_file_contents`.
    r   Tr   r   r   r   rbNr   r   FzFile 'z-' cannot be parsed as valid Jupyter notebook.w)encodingnewline	 +0000r  r  write_through)"r   r   r   utcfromtimestampstatst_mtimeopenr   readlinedecode_bytesreadformat_file_contentsrM   r   r|   decoderS   r_   writer^   r]   utcnowr   rF   rC   rB   nullcontextioTextIOWrappersysstdoutbufferr*   detach)rm   r   r   r   r   thenheaderbufsrc_contentsr  r  dst_contentsfnowsrc_namedst_nameZdiff_contentsra   ra   rb   r     sZ    

0
,
(r   )r   r   )r   r   r   r   rZ   c                C   sP  t  }|du r(ttjj \}}}n|dd  }}}|}zRzt|| |d}W W tj	tj
j||dd}	|tjkr|r|d dkr|d7 }|	| nb|tjtjfv rt  }
d	| d
}d|
 d
}t||||}|tjkrt|}t|	}	|	| |	  dS  ty   Y W tj	tj
j||dd}	|tjkrb|rV|d dkrV|d7 }|	| nf|tjtjfv rt  }
d	| d
}d|
 d
}t||||}|tjkrt|}t|	}	|	| |	  dS 0 W tj	tj
j||dd}	|tjkr"|r|d dkr|d7 }|	| nf|tjtjfv rt  }
d	| d
}d|
 d
}t||||}|tjkr~t|}t|	}	|	| |	  ntj	tj
j||dd}	|tjkr|r|d dkr|d7 }|	| nf|tjtjfv rBt  }
d	| d
}d|
 d
}t||||}|tjkr8t|}t|	}	|	| |	  0 dS )a  Format file on stdin. Return True if changed.

    If content is None, it's read from sys.stdin.

    If `write_back` is YES, write reformatted code back to stdout. If it is DIFF,
    write a diff to stdout. The `mode` argument is passed to
    :func:`format_file_contents`.
    Nutf-8 r  Tr  r   r   zSTDIN	r  zSTDOUT	F)r   r  r  r  stdinr  r  r  r  r  r  rS   r_   r  r^   r]   rC   rB   r*   r  rM   )r   r   r   r   r  rm   r  r  dstr   r!  r"  r#  dra   ra   rb   r   Z  s    






r   )r  r  r   rZ   c                C   s   t | | t| ||d dS )zPerform stability and equivalence checks.

    Raise AssertionError if source and destination contents are not
    equivalent, or if a second pass of the formatter would format the
    content differently.
    r   N)assert_equivalentassert_stable)r  r  r   ra   ra   rb   check_stability_and_equivalence  s    	
r,  )r  r   r   rZ   c                C   sJ   |j rt| ||d}nt| |d}| |kr.t|sF|j sFt| ||d |S )a   Reformat contents of a file and return new contents.

    If `fast` is False, additionally confirm that the reformatted code is
    valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
    `mode` is passed to :func:`format_str`.
    r  r)  )r   format_ipynb_string
format_strrM   r,  )r  r   r   r  ra   ra   rb   r    s    
r  )rm   r   rZ   c                    sP   t  fddtD rt dd dkrL  d dd t|jB vrLtdS )a  Check that cell does not already contain TransformerManager transformations,
    or non-Python cell magics, which might cause tokenizer_rt to break because of
    indentations.

    If a cell contains ``!ls``, then it'll be transformed to
    ``get_ipython().system('ls')``. However, if the cell originally contained
    ``get_ipython().system('ls')``, then it would get transformed in the same way:

        >>> TransformerManager().transform_cell("get_ipython().system('ls')")
        "get_ipython().system('ls')
"
        >>> TransformerManager().transform_cell("!ls")
        "get_ipython().system('ls')
"

    Due to the impossibility of safely roundtripping in such situations, cells
    containing transformed magics will be ignored.
    c                 3   s   | ]}| v V  qd S r[   ra   )rt   Ztransformed_magicrm   ra   rb   	<genexpr>  r   z validate_cell.<locals>.<genexpr>NrU   z%%r   )anyr,   rM   r   r+   r   )rm   r   ra   r/  rb   validate_cell  s    r2  )rm   r   r   rZ   c          
      C   s   t | | t| \}}zt|\}}W n ty>   tdY n0 t||d}|s^t|||d t||}t||}	|		d}	|	| krtd|	S )a  Format code in given cell of Jupyter notebook.

    General idea is:

      - if cell has trailing semicolon, remove it;
      - if cell has IPython magics, mask them;
      - format cell;
      - reinstate IPython magics;
      - reinstate trailing semicolon (if originally present);
      - strip trailing newlines.

    Cells with syntax errors will not be processed, as they
    could potentially be automagics or multi-line magics, which
    are currently not supported.
    Nr)  r   )
r2  r0   r.   SyntaxErrorrM   r.  r,  r1   r/   rstrip)
rm   r   r   Zsrc_without_trailing_semicolonZhas_trailing_semicolonZ
masked_srcreplacementsZ
masked_dstZdst_without_trailing_semicolonr'  ra   ra   rb   format_cell  s&    


r6  )nbrZ   c                 C   s6   |  di  di  dd}|dur2|dkr2tddS )zIf notebook is marked as non-Python, don't format it.

    All notebook metadata fields are optional, see
    https://nbformat.readthedocs.io/en/latest/format_description.html. So
    if a notebook has empty metadata, we will try to parse it anyway.
    metadataZlanguage_infor   Npython)rz   rM   )r7  languagera   ra   rb   validate_metadata  s    r;  c          
   	   C   s   | st | d dk}d}t| }t| |d D ]\}|dddkr2z d|d	 }t|||d
}W n t yx   Y q20 |jdd|d	< d}q2|rtj|ddd}	|r|	d }	|	S t dS )zFormat Jupyter notebook.

    Operate cell-by-cell, only on code cells, only for Python notebooks.
    If the ``.ipynb`` originally had a trailing newline, it'll be preserved.
    r   r   FcellsZ	cell_typeNr   r%  r   r  T)keependsrT   )indentensure_ascii)	rM   jsonloadsr;  rz   r   r6  
splitlinesdumps)
r  r   r   Ztrailing_newlinemodifiedr7  cellrm   r'  r  ra   ra   rb   r-    s*    
r-  )r  r   rZ   c                C   s$   t | |d}| |kr t ||dS |S )a  Reformat a string and return new contents.

    `mode` determines formatting options, such as how many characters per line are
    allowed.  Example:

    >>> import black
    >>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode()))
    def f(arg: str = "") -> None:
        ...

    A more complex example:

    >>> print(
    ...   black.format_str(
    ...     "def f(arg:str='')->None: hey",
    ...     mode=black.Mode(
    ...       target_versions={black.TargetVersion.PY36},
    ...       line_length=10,
    ...       string_normalization=False,
    ...       is_pyi=False,
    ...     ),
    ...   ),
    ... )
    def f(
        arg: str = '',
    ) -> None:
        hey

    r)  )_format_str_once)r  r   r  ra   ra   rb   r.    s    r.  c                   s0  t |  |j}g }|jr"|j nt|}t||d  fddtjhD }t| t||d}t	|d} fddtj
tjhD }d }	||D ]<}
||
}	||	 t|
||dD ]}|	jt| qq|rd|d _g }|D ]}	||	  q|s&t| d	\}}}d
|v r"|S dS d|S )Nfuture_importsc                    s   h | ]}t  |r|qS ra   r<   rt   featurer   ra   rb   	<setcomp>I  s   
z#_format_str_once.<locals>.<setcomp>)r   featuresr)  c                    s   h | ]}t  |r|qS ra   rI  rJ  rL  ra   rb   rM  Q  s   
r   r   r$  r   r%  )rI   lstripr   get_future_importsdetect_target_versionsr9   PARENTHESIZED_CONTEXT_MANAGERSr   r3   r5   TRAILING_COMMA_IN_CALLTRAILING_COMMA_IN_DEFvisitZmaybe_empty_linesappendr4   Zcontent_linesrs   afterextendZ	all_linesr  encoder   )r  r   Zsrc_nodeZ
dst_blocksrH  Zcontext_manager_featureslineseltZsplit_line_featuresblockcurrent_lineliner  Znormalized_content_r  ra   rL  rb   rF  @  sD    








rF  )rm   rZ   c                 C   s   t | }t|j\}}|s(d|dfS d|d dd kr@dnd}|d t ||}| ||fW  d   S 1 s~0    Y  dS )zReturn a tuple of (decoded_contents, encoding, newline).

    `newline` is either CRLF or LF but `decoded_contents` is decoded with
    universal newlines (i.e. only contains LF).
    r%  r   s   
r   Nz
)r  BytesIOtokenizedetect_encodingr  seekr  r  )rm   Zsrcbufr  rZ  r  Ztiowra   ra   rb   r  m  s    


r  rG  )noderH  rZ   c                C   s  t  }|r|dd |D O }|  D ]}t|r|jdd }|dv r|tj tj|vrt|jD ]4\}}|j||d  	 
drh|tj  qqhq$t|rd|jv r|tj q$|jtjkr|jr|jjtjtjtjhv r|tj q$|jtjkr|tj q$|jtjkrPt|jdkrt|jd s|tj q$|jtjtjhv r|jr|jd	 jtjkr|jtjkrtj}ntj}|jD ]N}|jt v r|| |jtj!kr|jD ]}	|	jt v r|| qАqq$|jtj"tj#hv rVt|jdkrV|jd jtj$krVt%d
d |jd jD rV|tj& q$|jtj'krt|jdkr|jd jtj$kr|tj( q$|jtj)kr&t|jdkr&|jd jtj*kr&|jd j}
t|
dkr|
d jtj+kr|
d jtj,kr|
d jtj-kr|tj. q$|jtj/krB|tj0 q$|jtj1krt|jdkr|jd jtj2kr|tj3 q$|jtj4tj5hv rt%dd |jD r|tj6 q$|jtj7kr$t|jdkr$|jd jtj8kr$|tj6 q$|S )aY  Return a set of (relatively) new Python features used in this file.

    Currently looking for:
    - f-strings;
    - self-documenting expressions in f-strings (f"{x=}");
    - underscores in numeric literals;
    - trailing commas after * or ** in function signatures and calls;
    - positional only arguments in function signatures and lambdas;
    - assignment expression;
    - relaxed decorator syntax;
    - usage of __future__ flags (annotations);
    - print / exec statements;
    - parenthesized context managers;
    - match statements;
    - except* clause;
    - variadic generics;
    c                 S   s   h | ]}|t v rt | qS ra   )r7   )rt   Zfuture_importra   ra   rb   rM    s   z$get_features_used.<locals>.<setcomp>NrU   >   zF"rfzf"zF'zf'ZRFfrZFRrT   =r_  r   c                 s   s   | ]}|j tjkV  qd S r[   r   rA   	star_exprrt   childra   ra   rb   r0    r   z$get_features_used.<locals>.<genexpr>rW   rV   r   c                 s   s   | ]}|j tjkV  qd S r[   ri  rk  ra   ra   rb   r0    s   )9r   Z	pre_orderr@   rl   r   r9   Z	F_STRINGSZDEBUG_F_STRINGSrO   r4  endswithr>   ZNUMERIC_UNDERSCORESr   rP   SLASHparentrA   ZtypedargslistZarglistZvarargslistZPOS_ONLY_ARGUMENTS
COLONEQUALZASSIGNMENT_EXPRESSIONS	decoratorr   childrenr?   ZRELAXED_DECORATORSCOMMArT  rS  r=   argumentZreturn_stmtZ
yield_exprZtestlist_star_exprr1  ZUNPACKING_ON_FLOWZ	annassignZANN_ASSIGN_EXTENDED_RHSZ	with_stmtZatomLPARZtestlist_gexpRPARrR  Z
match_stmtZPATTERN_MATCHINGZexcept_clauseSTARZEXCEPT_STARZsubscriptlisttrailerZVARIADIC_GENERICSZ
tname_starrj  )re  rH  rN  nZ
value_headZspan_begZspan_endrK  chZargchZatom_childrenra   ra   rb   get_features_used~  s    










r{  c                   s   t | |d  fddtD S )z5Detect the version to target based on the nodes used.rG  c                    s   h | ]} t | kr|qS ra   )r8   )rt   r   rN  ra   rb   rM    s   z)detect_target_versions.<locals>.<setcomp>)r{  r;   )re  rH  ra   r|  rb   rQ    s    
rQ  )re  rZ   c                    s   t  }tt ttddf d fdd | jD ]}|jtjkrB q|jd }t	|t
rt|jdkr|jtjkr|jd jtjkrq. qq.|jtjkr|jd }t	|t
r|jdkr q|t  |jd	d O }q. qq.|S )
z/Return a set of __future__ imports in the file.N)rr  rZ   c                 3   s   | D ]}t |tr(|jtjkr|jV  q|jtjkrn|jd }t |tsPJ d|jtjksdJ d|jV  q|jtj	kr |jE d H  qt
dqd S )Nr   zInvalid syntax parsing imports)rp   rQ   r   rP   NAMErl   rA   Zimport_as_namerr  Zimport_as_namesAssertionError)rr  rl  Z	orig_nameget_imports_from_childrenra   rb   r    s    



z5get_future_imports.<locals>.get_imports_from_childrenr   rU   rT   
__future__rV   )r   r   r2   r
   rs   rr  r   rA   Zsimple_stmtrp   rQ   r   rP   STRINGNEWLINEZimport_fromrl   )re  Zimportsrl  Zfirst_childmodule_namera   r  rb   rP    s,    "




rP  )rm   r'  rZ   c              
   C   s   zt | }W n6 tyB } ztd| d|W Y d}~n
d}~0 0 zt |}W nR ty } z:tdt|j|}td| d| dW Y d}~n
d}~0 0 dt|}dt|}||krtt	||dd	}td
| ddS )z:Raise AssertionError if `src` and `dst` aren't equivalent.zCcannot use --safe with this file; failed to parse source file AST: z~
This could be caused by running Black with an older Python version that does not support new syntax used in your source file.Nr%  z-INTERNAL ERROR: Black produced invalid code: ze. Please report a bug on https://github.com/psf/black/issues.  This invalid output might be helpful: r   rm   r'  zINTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: )
rJ   r   r~  rD   r   r   	format_tb__traceback__rK   rC   )rm   r'  Zsrc_astr   Zdst_astlogZsrc_ast_strZdst_ast_strra   ra   rb   r*  ?  s@    r*  )rm   r'  r   rZ   c                 C   sL   t ||d}||krHtt|t| |ddt||dd}td| ddS )zDRaise AssertionError if `dst` reformats differently the second time.r)  r   z
first passzsecond passzINTERNAL ERROR: Black produced different code on the second pass of the formatter.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: N)rF  rD   rs   rC   r~  )rm   r'  r   Znewdstr  ra   ra   rb   r+  `  s    r+  )rZ   c                   c   s
   dV  dS )zWReturn an empty context manager.

    To be used like `nullcontext` in Python 3.7.
    Nra   ra   ra   ra   rb   r  s  s    r  c                  C   s   g } zddl m} W n ty&   Y n0 | | zddl m} W n tyT   Y n0 | | | D ],}t|dr|dd |_t|drddd |_qdd	S )
a  Make Click not crash on Python 3.6 with LANG=C.

    On certain misconfigured environments, Python 3 selects the ASCII encoding as the
    default which restricts paths that it can access during the lifetime of the
    application.  Click refuses to work in this scenario by raising a RuntimeError.

    In case of Black the likelihood that non-ASCII characters are going to be used in
    file paths is minimal since it's Python source code.  Moreover, this crash was
    spurious on Python 3.7 thanks to PEP 538 and PEP 540.
    r   )core)_unicodefun_verify_python3_envc                   S   s   d S r[   ra   ra   ra   ra   rb   <lambda>  r   zpatch_click.<locals>.<lambda>_verify_python_envc                   S   s   d S r[   ra   ra   ra   ra   rb   r    r   N)r}   r  ImportErrorrV  r  hasattrr  r  )modulesr  r  modulera   ra   rb   patch_click|  s     




r  c                  C   s.   t tddrddlm}  |   t  t  d S )NfrozenFr   freeze_support)getattrr  multiprocessingr  r  r   r  ra   ra   rb   patched_main  s
    r  __main__)r  r@  platformr   r  rb  r   
contextlibr   Zdataclassesr   r   enumr   Zjson.decoderr   pathlibr   typingr   r	   r
   r   r   r   r   r   r   r   r   r   r   r}   Z
click.corer   Zmypy_extensionsr   Zpathspecr   Zpathspec.patterns.gitwildmatchr   Z_black_versionr   r   Zblack.cacher   r   r   r   Zblack.commentsr   Zblack.constr   r    r!   r"   Zblack.filesr#   r$   r%   r&   r'   r(   r)   r*   Zblack.handle_ipynb_magicsr+   r,   r-   r.   r/   r0   r1   Zblack.linegenr2   r3   r4   Zblack.linesr5   r6   Z
black.moder7   r8   r9   r:   r;   r<   Zblack.nodesr=   r>   r?   r@   rA   Zblack.outputrB   rC   rD   rE   rF   rG   Zblack.parsingrH   rI   rJ   rK   Zblack.reportrL   rM   rN   Zblack.transrO   Zblib2to3.pgen2rP   Zblib2to3.pytreerQ   rR   __file__r   ZCOMPILEDrs   ZFileContentEncodingZNewLinerS   ZFileModeContext	Parameterr   Optionr   r   r   commandoptionintZChoicer   sortedZIntRangeZversion_optionpython_implementationpython_versionrt  Zpass_contextri   r   r   r   r   r   rg   r   r   r,  r  r2  r6  r;  r-  r.  rF  bytesr  r{  rQ  rP  r*  r+  r  r  r  rd   ra   ra   ra   rb   <module>   s  <(
$	  /


					
		
	



F F



S

7C4% '- 
2!"
