o
    h!                  X   @   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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 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/ d dl0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ d dlAmBZBmCZCmDZDmEZEmFZFmGZGmHZH d dlImJZJmKZKmLZL d dlMmNZNmOZO d dlPmQZQmRZRmSZS d dlPmTZT d dlPmUZUmVZV 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lmmnZnmoZompZp d dlqmrZr d dlsmtZt d d lumvZvmwZw eexjyd!v Zze{Z|e{Z}e{Z~G d"d# d#eZeTZd$e"jd%e"jd&ee{ d'ee{ fd(d)Zd*e"jd+e!e"je"jf d,e e{d-f d'eeU fd.d/Zd0e{d'ee{ fd1d2Zd$e"jd%e"jd&ee{ d'eee{  fd3d4Ze"jd5d6d7gid8d9e"jd:d;e{d<d=e"jd>d?ee5d@dAdBe"jdCdDe"dEdF eUD edAdGdHe"jdIdAdJdKe"jdLdAdMdKe"jdNdAdOdPeeB dQg dRe"jdSdTdAdUdKe"jdVdWdAdXdKe"jdYdZdAd[dKe"jd\dAdAd]d^e"jd_dAd`dKe"jdadAdbdKe"jdcdAdddKe"jdedAdfdgdhdie"jdjdAdkdKe"jdldAdmdKe"jdne{dod=e"jdpe{e4edqdAdre"jdse{edte3 dudvdwe"jdxe{edydze"jd{e{ed|dze"jd}e{dAd~de"jdde"jddddde"jdddAddKe"jdddAddKe"je-dezrdnd de  de  de"jdde"jdAdAdAdAdAddAdde"jde"jdAdAdvdAdve{ddAedde"jd$e"jdee{ dedeeU dededee{ dededededee{ dedededededededee{ dee{ deee{  deee{  deee{  dee{ dee de e{d-f dee{ d'df:ddZdede e{d-f dededee{ deee{  deee{  deee{  dddee{ d'ee fddZdede{deded$e"jd'dfddZdhdde{dededeTdepdee eef  d'dfddńZe&dAdƍdhddedededeTdddee eef  d'dfddȄZejdfdhddededeTdededee eef  d'efdd˄Zdejdhd̜dedee{ dedeTdee eef  d'efdd΄Zdhdde{de{deTdee eef  d'df
dd҄Zdhdde{dedeTdee eef  d'e|f
ddԄZde{deTd'dfddքZde{dedeTd'e{fdd؄Zdee{ef d'dfddۄZde{dedeTd'e|fdd݄Zdhdde{deTdee eef  d'e{fdd߄Zdhdde{deTdee eef  d'e{fddZded'e e|e}e~f fddZdddewdeee{  d'eeS fddZdddewdeee{  d'eeU fddZdewd'ee{ fddZde{de{d'dfddZdhdde{de{deTdee eef  d'df
ddZed'ed fddZdddZedkre  dS dS )    N)contextmanager)replace)datetimetimezone)Enum)JSONDecodeError)Path)Any
CollectionDict	GeneratorIteratorListMutableMappingOptionalPatternSequenceSetSizedTupleUnion)ParameterSource)
mypyc_attr)PathSpec)GitWildMatchPatternError)version)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path_is_excluded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)adjusted_linesconvert_unchanged_linesparse_line_ranges)ChangedNothingChangedReport)iter_fexpr_spans)token)LeafNode)z.pydz.soc                
   @   sD   e Zd ZdZdZdZdZdZeddde	d	e	d
e	dd fddZ
dS )	WriteBackr               F)colorcheckrC   r[   returnc                C   s,   |r|s| j S |r|r| jS |r| jS | jS N)CHECK
COLOR_DIFFDIFFYES)clsr\   rC   r[    rd   D/var/www/html/ai/venv/lib/python3.10/site-packages/black/__init__.pyfrom_configurationf   s
   zWriteBack.from_configurationN)__name__
__module____qualname__NOrb   ra   r_   r`   classmethodboolrf   rd   rd   rd   re   rV   _   s"    rV   ctxparamvaluer]   c           
   
   C   sH  |st | jdd| jdd}|du rdS zt|}W n ttfy6 } ztj|d| ddd}~ww |s;dS dd | D }|d	}|durXt	|t
sXtd
d|d}|durlt	|tsltdd|d}|durt	|tstdd|d}|durt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.
    srcrd   stdin_filenameNz"Error reading configuration file: )filenamehintc                 S   s,   i | ]\}}|t |ttfst|n|qS rd   )
isinstancelistdictstr).0kvrd   rd   re   
<dictcomp>   s    z'read_pyproject_toml.<locals>.<dictcomp>target_versionztarget-versionz(Config key target-version must be a listexcludez#Config key exclude must be a stringextend_excludezextend-excludez*Config key extend-exclude must be a stringline_rangeszline-rangesz2Cannot use line-ranges in the pyproject.toml file.)r#   paramsgetr(   OSError
ValueErrorclick	FileErroritemsrt   ru   BadOptionUsagerw   default_mapupdate)
rm   rn   ro   configer|   r}   r~   r   r   rd   rd   re   read_pyproject_tomlw   sZ   





r   cprz   .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 rd   )r;   upper)rx   valrd   rd   re   
<listcomp>   s    z2target_version_option_callback.<locals>.<listcomp>rd   )r   r   rz   rd   rd   re   target_version_option_callback   s   r   regexc                 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   compiledrd   rd   re   re_compile_maybe_verbose   s   
r   c              
   C   sF   z|d ur
t |W S d W S  tjy" } z	td| d d }~ww )Nz Not a valid regular expression: )r   r   errorr   BadParameter)rm   rn   ro   r   rd   rd   re   validate_regex   s   r   help_option_namesz-hz--help"The uncompromising code formatter.)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 rd   )namelower)rx   rz   rd   rd   re   r      s    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 (z, 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--line-rangesz	START-ENDaB  When specified, _Black_ will try its best to only format these lines. This option can be specified multiple times, and a union of the lines will be formatted. Each range must be specified as two integers connected by a `-`: `<START>-<END>`. The `<START>` and `<END>` integer indices are 1-based and inclusive on both ends.rd   )r   metavarr   r   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.)r   is_eagerr   z-Wz	--workersrW   )minzlNumber of parallel workers [default: BLACK_NUM_WORKERS environment variable or 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   messagerp   )exists	file_okaydir_okayreadable
allow_dashzSRC ...)nargsr   r   r   z--config)r   r   r   r   r   	path_typez"Read configuration from FILE path.)r   r   r   r   codeline_lengthr|   r\   rC   r   r[   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includer}   r~   force_excluderq   workersr   c           +      C   s  |  t |r|durtt| d  | d |s-|du r-tt| d  | d |du r6t||nd\}}|| jd< |r|rPtd| d| d	d
d |r| d}t	t
 }||krktd| dd
d n|tjtjfv rztdd
d n
td| dd
d | jr| j D ]\} }!t|  d|!  qd}"|r|tkr|td	d krt|" d| dt d | d |
r|	rtd | d tj|||d}#|rt|}$nt }$t|$||	|
|| | ||t|d
}%g }&|r#|
rtd | d zt|}&W n ty" }' ztt	|' | d W Y d}'~'nd}'~'ww |dur*d}t||||d}(|durBt|||#|%|(|&d n_|dusIJ zt|||||||||(|d
})W n tyh   | d Y nw t|)d|||  t|)dkrt|)  ||#|%|(|&d  ndd!l!m"}* |&rtd" | d |*|)||#|%|(|d# |s|s|du r|s|(j#s|(j$rt  t|(j%r|"nd$ |du rt&j't	|(dd% | |(j% dS )&r   Nz3

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

One of 'SRC' or 'code' is required.)NNrootzIdentified `z` as project root containing a .bluefgr   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!)r\   rC   r[   )
target_versionsr   is_pyiis_ipynbr   string_normalizationmagic_trailing_commar   r   r   z*Cannot use --line-ranges with ipynb files.T)r\   rC   r   r   )contentr   
write_backmodereportlines)
r   rp   r   r   r   r}   r~   r   r   rq   u?   No Python files are present to be formatted. Nothing to do 😴)rp   r   r   r   r   r   )reformat_manyz2Cannot use --line-ranges to format multiple files.)sourcesr   r   r   r   r   u   All done! ✨ 🍰 ✨)rE   )(ensure_objectrv   rG   main	get_usageexitr"   objget_parameter_sourcerw   r$   r   DEFAULTDEFAULT_MAPr   r   __version__splitrE   rV   rf   setr:   rN   r   rQ   reformat_codeget_sourcesr   
path_emptylenreformat_onepopblack.concurrencyr   change_countfailure_countreturn_coder   echo)+rm   r   r   r|   r\   rC   r   r[   r   r   r   r   r   r   r   r   r   r   r   r   r   r}   r~   r   rq   r   rp   r   r   methodconfig_sourceuser_level_configrn   ro   	error_msgr   versionsr   r   r   r   r   r   rd   rd   re   r      s&    











	
	
	 
r   r   r   rQ   c        
         C   s  t  }
|du }|du rttn|}d}t| }|D ]}|dkr(|	r(t|	}d}nt|}d}|s4| r| |  }d| }t	||rM|
|d qt|| |}|du rd|rctd| dd	d
 q|rptt t| }|jdkr~t|pz| ds~q|rtd| ddd
 |
| q| r| | |  }|rtd| ddd
 |r| ||t|i}|
t| | ||||||||d
 q|dkr|rtddd
 |
| qtd|  q|
S )z)Compute the set of files to be formatted.N-TF/z.matches the --force-exclude regular expressionzSkipping invalid source: ""redr   .ipynb)warnzFound input source: "r   zFound input source directory: ")r   r   zFound input source stdinzinvalid path: )r   r   r   r&   r   is_fileabsoluterelative_toas_posixr)   path_ignoredr'   rG   r!   rw   suffixr-   addis_dirresolver   r%   iterdirrE   )r   rp   r   r   r   r}   r~   r   r   rq   r   using_default_exclude	gitignoreroot_gitignorespathis_stdinroot_relative_pathnormalized_pathrd   rd   re   r     s~   
r   msgc                 C   s&   | s|s|s
t | |d dS dS )z;
    Exit if there is no `src` provided for formatting
    r   N)rG   r   )rp   r  r   r   rm   rd   rd   re   r     s
   r   )r   r   r   r   r   c          	   
   C   s~   t d}ztj}t| ||||drtj}||| W dS  ty> } z|jr+t	  |
|t| W Y d}~dS d}~ww )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   r   N)r   rO   rj   format_stdin_to_stdoutrb   done	Exceptionr   	traceback	print_excfailedrw   )	r   r   r   r   r   r   r	  changedexcrd   rd   re   r     s   
r   )	patchablec          
   
   C   sj  zt j}t| dkrd}nt| tr#d}tt| ttd } nd}|rJ| jdkr3t|dd}n| jdkr>t|dd}t	||||d	rIt j
}n@t|}|tjtjfvr_|| s_t j}|t jurpt| ||||d	rpt j
}|tj
u rz|t jus|tju r|t ju r|| g || | W dS  ty }	 z|jrt  || t|	 W Y d}	~	dS d}	~	ww )
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   r   )rO   rj   rw   
startswithr!   r   r   r   r   r  rb   r   readrV   ra   r`   
is_changedCACHEDformat_file_in_placer_   writer  r  r   r  r  r  )
rp   r   r   r   r   r   r  r
  cacher  rd   rd   re   r     sH   




r   lockc                C   s  | j dkrt|dd}n| j dkrt|dd}t|  jtj}d}t| d}|j	r0|
 }t| \}	}
}W d   n1 sCw   Y  z
t|	|||d	}W n ty\   Y d
S  tyk   td|  ddw ||
|	 }	||
| }|tjkrt| d|
|d}|| W d   dS 1 sw   Y  dS |tjtjfv rttj}|  d| }|  d| }|jrt|	|||}nt|	|||}|tjkrt|}|pt ! tjtj j!|
|dd}t"|}|| |#  W d   dS 1 sw   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      rbNr   r   r   FzFile 'z-' cannot be parsed as valid Jupyter notebook.w)encodingnewline	r&  r'  write_through)$r   r   r   fromtimestampstatst_mtimer   utcopenr   readlinedecode_bytesr  format_file_contentsrP   r   r   decoderV   rb   r  ra   r`   nowr   rF   rC   rB   nullcontextioTextIOWrappersysstdoutbufferr*   detach)rp   r   r   r   r!  r   thenheaderbufsrc_contentsr&  r'  dst_contentsfr4  src_namedst_namediff_contentsrd   rd   re   r  T  sp   









r  )r   r   r   c                C   s  t tj}|du rttjj \}}}n|dd}}}|}	zzct	|| ||d}	W W t
jtjj||dd}
|tjkrN|	rH|	d dkrH|	d7 }	|
|	 n1|tjtjfv rt tj}d	| }d
| }t||	||}|tjkrzt|}t|
}
|
| |
  dS  ty   Y W t
jtjj||dd}
|tjkr|	r|	d dkr|	d7 }	|
|	 n1|tjtjfv rt tj}d	| }d
| }t||	||}|tjkrt|}t|
}
|
| |
  dS w t
jtjj||dd}
|tjkr|	r|	d dkr|	d7 }	|
|	 n3|tjtjfv r?t tj}d	| }d
| }t||	||}|tjkr:t|}t|
}
|
| |
  w )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	zSTDOUT	F)r   r4  r   r.  r1  r8  stdinr:  r  r2  r6  r7  r9  rV   rb   r  ra   r`   rC   rB   r*   r;  rP   )r   r   r   r   r   r<  rp   r&  r'  dstrA  r4  rB  rC  drd   rd   re   r    s|   













r  r?  r@  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   r   N)assert_equivalentassert_stable)r?  r@  r   r   rd   rd   re   check_stability_and_equivalence  s   
rM  c                C   sN   |j rt| ||d}nt| ||d}| |krt|s%|j s%t| |||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   rJ  )r   format_ipynb_string
format_strrP   rM  )r?  r   r   r   r@  rd   rd   re   r2    s   
r2  c                    sT   t  fddtD rt dd dkr&  d dd t|jB vr(tdS 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^   rd   )rx   transformed_magicrp   rd   re   	<genexpr>
  s    z validate_cell.<locals>.<genexpr>NrX   z%%r   )anyr,   rP   r   r+   r   )rp   r   rd   rR  re   validate_cell  s   rU  c          
      C   s   t | | t| \}}zt|\}}W n
 ty   tdw t||d}|s-t|||d t||}t||}	|		d}	|	| krCt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.
    Nr   r   )
rU  r0   r.   SyntaxErrorrP   rP  rM  r1   r/   rstrip)
rp   r   r   src_without_trailing_semicolonhas_trailing_semicolon
masked_srcreplacements
masked_dstdst_without_trailing_semicolonrH  rd   rd   re   format_cell  s(   


r_  nbc                 C   s:   |  di  di  dd}|dur|dkrtddS 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.
    metadatalanguage_infor   Npython)r   rP   )r`  languagerd   rd   re   validate_metadata8  s   re  c          
   	   C   s   | st | d dk}d}t| }t| |d D ].}|dddkrGzd|d	 }t|||d
}W n	 t y<   Y qw |jdd|d	< d}q|rZtj|ddd}	|rX|	d }	|	S t )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cells	cell_typeNr   rF  sourcerN  T)keependsrW   )indentensure_ascii)	rP   jsonloadsre  r   joinr_  
splitlinesdumps)
r?  r   r   trailing_newlinemodifiedr`  cellrp   rH  r@  rd   rd   re   rO  D  s.   
rO  c                C   s8   t | ||d}| |kr|rt|| |}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

    rJ  )_format_str_oncerL   )r?  r   r   r@  rd   rd   re   rP  d  s    rP  c                   s<  t |  |j}g }|jr|j n
t|}t||d  fddtjhD }t|| |r2t|| t	||d}t
|d} fddtjtjhD }	d }
||D ]}||}
||
 t|||	dD ]
}|
jt| qdqQ|rwd|d _g }|D ]	}
||
  q{|st| d	\}}}d
|v r|S dS d|S )Nfuture_importsc                       h | ]	}t  |r|qS rd   r<   rx   featurer   rd   re   	<setcomp>      z#_format_str_once.<locals>.<setcomp>)r   featuresrV  c                    rw  rd   rx  ry  r{  rd   re   r|    r}  r   r   rE  r   rF  )rI   lstripr   get_future_importsdetect_target_versionsr9   PARENTHESIZED_CONTEXT_MANAGERSr   rM   r3   r5   TRAILING_COMMA_IN_CALLTRAILING_COMMA_IN_DEFvisitmaybe_empty_linesappendr4   content_linesrw   afterextend	all_linesr1  encodern  )r?  r   r   src_node
dst_blocksrv  context_manager_featuresline_generatoreltsplit_line_featuresblockcurrent_lineliner@  normalized_content_r'  rd   r{  re   rt    sJ   










rt  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?w   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).
    rF  r   s   
r   Nz
)r6  BytesIOtokenizedetect_encodingr0  seekr7  r  )rp   srcbufr&  r   r'  tiowrd   rd   re   r1    s   


$r1  ru  noderv  c                C   s  t  }|r|dd |D O }|  D ]}t|rP|jdd }|dv rO|tj tj|vrOt|jD ]\}}|j||d  	 
drN|tj  nq4qt|r`d|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rt|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 ]"}|jt v r|| |jtj!kr|jD ]}	|	jt v r|| qqq|jtj"tj#hv rt|jdkr|jd jtj$krt%d
d |jd jD r|tj& q|jtj'kr>t|jdkr>|jd jtj$kr>|tj( q|jtj)krt|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r|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rt|jdkr|jd jtj8kr|tj6 q|jtj9tj:fv r |tj; 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 rd   )r7   )rx   future_importrd   rd   re   r|    s
    z$get_features_used.<locals>.<setcomp>NrX   >   F"F'f"f'FRRFfrrfrW   =r  r   c                 s       | ]	}|j tjkV  qd S r^   r   rA   	star_exprrx   childrd   rd   re   rS  &  s    z$get_features_used.<locals>.<genexpr>rZ   rY   r   c                 s   r  r^   r  r  rd   rd   re   rS  I  s    
)<r   	pre_orderr@   ro   r  r9   	F_STRINGSDEBUG_F_STRINGSrR   rX  endswithr>   NUMERIC_UNDERSCORESr   rS   SLASHparentrA   typedargslistarglistvarargslistPOS_ONLY_ARGUMENTS
COLONEQUALASSIGNMENT_EXPRESSIONS	decoratorr   childrenr?   RELAXED_DECORATORSCOMMAr  r  r=   argumentreturn_stmt
yield_exprtestlist_star_exprrT  UNPACKING_ON_FLOW	annassignANN_ASSIGN_EXTENDED_RHS	with_stmtatomLPARtestlist_gexpRPARr  
match_stmtPATTERN_MATCHINGexcept_clauseSTAREXCEPT_STARsubscriptlisttrailerVARIADIC_GENERICS
tname_starr  	type_stmt
typeparamsTYPE_PARAMS)r  rv  r~  n
value_headspan_begspan_endrz  chargchatom_childrenrd   rd   re   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.ru  c                    s   h | ]
} t | kr|qS rd   )r8   )rx   r   r~  rd   re   r|  `  s    z)detect_target_versions.<locals>.<setcomp>)r  r;   )r  rv  rd   r  re   r  [  s   
r  c                    s   t  }dtt dttddf f fdd | jD ]W}|jtjkr# |S |jd }t	|t
rGt|jdkrD|jtjkrD|jd jtjkrDq |S |jtjkrm|jd }t	|t
r\|jd	kr_ |S |t  |jd
d O }q |S |S )z/Return a set of __future__ imports in the file.r  r]   Nc                 3   s    | D ]G}t |tr|jtjkr|jV  q|jtjkr8|jd }t |ts)J d|jtjks3J d|jV  q|jtj	krG |jE d H  qt
dd S )Nr   zInvalid syntax parsing imports)rt   rT   r   rS   NAMEro   rA   import_as_namer  import_as_namesAssertionError)r  r  	orig_nameget_imports_from_childrenrd   re   r  i  s   


z5get_future_imports.<locals>.get_imports_from_childrenr   rX   rW   
__future__rY   )r   r   r2   r   rw   r  r   rA   simple_stmtrt   rT   r   rS   STRINGNEWLINEimport_fromro   )r  importsr  first_childmodule_namerd   r  re   r  e  s,   $



r  rH  c              
   C   s   zt | }W n ty } z	td| d|d}~ww zt |}W n# tyE } ztdt|j|}td| d| dd}~ww dt|}dt|}||krit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.NrF  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   rp   rH  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   rn  r  	format_tb__traceback__rK   rC   )rp   rH  src_astr  dst_astlogsrc_ast_strdst_ast_strrd   rd   re   rK    sJ   rK  c                C   s^   |rt || |}t|||d}||kr-tt|t| |ddt||dd}td| ddS )zDRaise AssertionError if `dst` reformats differently the second time.rJ  rh  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)rL   rt  rD   rw   rC   r  )rp   rH  r   r   newdstr  rd   rd   re   rL    s"   rL  c                   c   s    dV  dS )zWReturn an empty context manager.

    To be used like `nullcontext` in Python 3.7.
    Nrd   rd   rd   rd   re   r5    s   
r5  c                  C   s(   t tddrddlm}  |   t  d S )NfrozenFr   freeze_support)getattrr8  multiprocessingr  r   r  rd   rd   re   patched_main  s   
r  __main__)r]   N)r6  rl  platformr   r8  r  r  
contextlibr   dataclassesr   r   r   enumr   json.decoderr   pathlibr   typingr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   
click.corer   mypy_extensionsr   pathspecr   pathspec.patterns.gitwildmatchr   _black_versionr   r   black.cacher   black.commentsr   black.constr   r   r    r!   black.filesr"   r#   r$   r%   r&   r'   r(   r)   r*   black.handle_ipynb_magicsr+   r,   r-   r.   r/   r0   r1   black.linegenr2   r3   r4   black.linesr5   r6   
black.moder7   r8   r9   r:   r;   r<   black.nodesr=   r>   r?   r@   rA   black.outputrB   rC   rD   rE   rF   rG   black.parsingrH   rI   rJ   rK   black.rangesrL   rM   rN   black.reportrO   rP   rQ   black.transrR   blib2to3.pgen2rS   blib2to3.pytreerT   rU   __file__r   COMPILEDrw   FileContentEncodingNewLinerV   FileModeContext	Parameterr   Optionr   r   r   commandoptionintChoicern  sortedIntRangeversion_optionpython_implementationpython_versionr  pass_contextrl   r   r   r   r   r   rj   r  r  rM  r2  rU  r_  re  rO  rP  rt  bytesr1  r  r  r  rK  rL  r5  r  rg   rd   rd   rd   re   <module>   s   @,$	 
@





				


		
		




F E



	

_

 <
G
9

%!
,
3

 



2"



