o
    ^i                  ^   @   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m	Z	m
Z
mZmZ d dlmZ d dlmZ d dlmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
l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l,m-Z- d dl.m/Z/m0Z0m1Z1m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= d dl>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZE d dlFmGZGmHZHmIZI d dlJmKZKmLZL d dlMmNZNmOZOmPZP d dlMmQZQ d dlMmRZRmSZSmTZT d dlUmVZVmWZWmXZXmYZY d dlZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z` d dlambZbmcZcmdZdmeZemfZf d dlgmhZhmiZimjZjmkZk d dllmmZmmnZnmoZo d dlpmqZq d d lrmsZsmtZt eeujvd!v ZwexZyexZzexZ{G d"d# d#eZ|eQZ}d$ej~d%ejd&eex d'eex fd(d)Zd$ej~d*eex d+exd'dfd,d-Zd.ej~d/eejejf d0eexd1f d'eeS fd2d3Zd.ej~d/eejejf d0eexd1f d'eeR fd4d5Zd6exd'eex fd7d8Zd$ej~d%ejd&eex d'eeex  fd9d:Zejd;d<d=gid>d?ejd@dAexdBdCejdDdEee1dFdGdHejdIdJedKdL eSD edGdMdNejdOdGdPdQejdRdGdSdQejdTdGdUdVee? dWg dXejdYdZdGd[dQejd\d]dGd^dQejd_d`dGdadQejdbdGdcdQejdddGdedQejdfedgdL eRD edGdhdNejdidGdjdQejdkdGdldQejdmdGdndQejdodGdpdqdrdsejdtdGdudQejdvexdwdCejdxexedye/ dzd{d|ejd}exed~dejdexeddejdexdGddejdexe0eddGdejddejdddddejdddGddQejdddGddQeje)dewrdnd de  de  dejddejdGdGdGdGdGddGddejdejdGdGd{dGd{exddGeddejddGddQejd$ej~deex dedeeS dededeex dededededeex dedededededeeR dededeex deex deeex  deeex  deeex  deex dee deexd1f deex ded'df>ddZdedeexd1f dededeex deeex  deeex  deeex  dddeex d'ee fddǄZdrdȜdexdede|deQdeodeeeef  d'dfdd΄Ze"dGdύdrd{dМdedede|deQdddeeeef  ded'dfdd҄Ze|jdfdrdȜdededeQde|dedeeeef  d'efddՄZde|jdrd֜dedeex de|deQdeeeef  d'efdd؄ZdrdȜdexdexdeQdeeeef  d'df
dd܄ZdrdȜdexdedeQdeeeef  d'eyf
ddބZdexdedeQd'exfddZdeexef d'dfddZdexdedeQd'eyfddZdrdȜdexdeQdeeeef  d'exfddZdrdȜdexdeQdeeeef  d'exfddZdedeQd'eeyeze{f fddZdddetdeeex  d'eeP fddZdeetesf d'efddZdddetdeeex  d'eeS fddZdetd'eex fddZd'exfddZdexdexd'dfddZdrdȜdexdexdeQdeeeef  d'df
ddZed'e
d fddZdd dZedkr_e  dS dS (      N)
Collection	GeneratorIteratorMutableMappingSequence)contextmanager)replace)datetimetimezone)Enum)JSONDecodeError)Path)Pattern)AnyOptionalUnion)ParameterSource)
mypyc_attr)PathSpec)GitWildMatchPatternError)version)Cache)normalize_fmt_off)DEFAULT_EXCLUDESDEFAULT_INCLUDESDEFAULT_LINE_LENGTHSTDIN_PLACEHOLDER)
best_effort_relative_pathfind_project_rootfind_pyproject_tomlfind_user_pyproject_tomlgen_python_filesget_gitignoreparse_pyproject_tomlpath_is_excluded$resolves_outside_root_or_cannot_statwrap_stream_for_windows)PYTHON_CELL_MAGICS"jupyter_dependencies_are_installed	mask_cellput_trailing_semicolon_backremove_trailing_semicolonunmask_cellvalidate_cell)LNLineGeneratortransform_line)EmptyLineTracker
LinesBlock)FUTURE_FLAG_TO_FEATUREVERSION_TO_FEATURESFeature)Mode)PreviewTargetVersionsupports_feature)STARSis_number_tokenis_simple_decorator_expressionsyms)
color_diffdiffdump_to_fileerr
ipynb_diffout)ASTSafetyErrorInvalidInputlib2to3_parse	parse_aststringify_ast)adjusted_linesconvert_unchanged_linesparse_line_rangessanitized_lines)ChangedNothingChangedReport)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checkr?   rX   returnc                C   s,   |r|s| j S |r|r| jS |r| jS | jS N)CHECK
COLOR_DIFFDIFFYES)clsrY   r?   rX    ra   S/var/www/html/stock_analysis/be/venv/lib/python3.10/site-packages/black/__init__.pyfrom_configurationc   s
   zWriteBack.from_configurationN)__name__
__module____qualname__NOr_   r^   r\   r]   classmethodboolrc   ra   ra   ra   rb   rS   \   s"    rS   ctxparamvaluerZ   c           
   
   C   sX  |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 t| t	|| dd |
 D }|d	}|dur`t|t	s`td
d|d}|durtt|tstt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.
    srcra   stdin_filenameNz"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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spellcheck_pyproject_toml_keysrr   itemsrq   BadOptionUsagert   default_mapupdate)
rj   rk   rl   configery   rz   r{   r|   r   ra   ra   rb   read_pyproject_tomlt   s\   





r   config_keysconfig_file_pathc                    s^   g }dd | j jD   fdd|D }|r-dtt|}td| d| dd	d
 d S d S )Nc                 S   s   h | ]}|j qS ra   name)ru   rk   ra   ra   rb   	<setcomp>       z1spellcheck_pyproject_toml_keys.<locals>.<setcomp>c                    s   g | ]}| vr|qS ra   ra   )ru   keyavailable_config_optionsra   rb   
<listcomp>       z2spellcheck_pyproject_toml_keys.<locals>.<listcomp>, zInvalid config keys detected: z (in )redfg)commandr}   joinmapreprrC   )rj   r   r   invalid_keyskeys_strra   r   rb   r      s   
r   cprw   .c                 C      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   )r8   upperru   valra   ra   rb   r      r   z2target_version_option_callback.<locals>.<listcomp>ra   r   r   rw   ra   ra   rb   target_version_option_callback   s   r   c                 C   r   )z<Compute the features from an --enable-unstable-feature flag.c                 S   s   g | ]}t | qS ra   )r7   r   ra   ra   rb   r      s    z4enable_unstable_feature_callback.<locals>.<listcomp>ra   r   ra   ra   rb    enable_unstable_feature_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   compiledra   ra   rb   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)rj   rk   rl   r   ra   ra   rb   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 ra   )r   lowerru   rw   ra   ra   rb   r      s    r   a!  Python versions that should be supported by Black's output. You should include all versions that your code supports. By default, Black will infer target versions 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--pyiz{Format all input files like typing stubs regardless of file extension. This is useful when piping source on standard input.)is_flagr   z--ipynbzFormat all input files like Jupyter Notebooks regardless of file extension. This is 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 (r   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	--previewzvEnable potentially disruptive style changes that may be added to Black's main functionality in the next major release.z
--unstablezEnable potentially disruptive style changes that have known bugs or are not currently expected to make it into the stable style Black's next major release. Implies --preview.z--enable-unstable-featurec                 C   s   g | ]}|j qS ra   r   r   ra   ra   rb   r   F  r   zEnable specific features included in the `--unstable` style. Requires `--preview`. No compatibility guarantees are provided on the behavior or existence of any unstable features.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--diffzDon't write the files back, just output a diff to indicate what changes Black would've made. They are printed to stdout so capturing them is simple.z--color/--no-colorzFShow (or do not show) colored diff. Only applies when --diff is given.z--line-rangesz	START-ENDa@  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.ra   )r   metavarr   r   z--fast/--safezBy default, Black performs an AST safety check after formatting your code. The --fast flag turns off this check and the --safe flag explicitly enables it. [default: --safe]z--required-versiona5  Require a specific version of Black to be running. This is useful for ensuring that all contributors to your project are using the same version, because different versions of Black may format code a little differently. This option can be set in a configuration file for consistent results across environments.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). By default, Black also ignores all paths listed in .gitignore. Changing this value will override all default exclusions. [default: ]F)r   r   r   r   z--extend-excludezrLike --exclude, but adds additional files and directories on top of the default values instead of overriding them.)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. This is useful when invoking Black programmatically on changed files, such as in a pre-commit hook or editor plugin.z--stdin-filenamezThe name of the file when passing it through stdin. Useful to make sure Black will respect the --force-exclude option on some editors that rely on using stdin.)r   is_eagerr   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). Overrides all exclusions, including from .gitignore and command line options.)r   r   r   r   r   z-Wz	--workersrT   )mina  When Black formats multiple files, it may use a process pool to speed up formatting. This option controls the number of parallel workers. This can also be specified via the BLACK_NUM_WORKERS environment variable. Defaults to the number of CPUs in the system.)r   r   r   z-qz--quietzpStop emitting all non-critical output. Error messages will still be emitted (which can silenced by 2>/dev/null).z-vz	--verbosezEmit messages about files that were not changed or were ignored due to exclusion patterns. If Black is using a configuration file, a message detailing which one it is using will be emitted.z!%(prog)s, %(version)s (compiled: yesnoz
)
Python () )r   messagerm   )exists	file_okaydir_okayreadable
allow_dashzSRC ...)nargsr   r   r   z--config)r   r   r   r   r   	path_typez5Read configuration options from a configuration file.)r   r   r   r   z
--no-cachezQSkip reading and writing the cache, forcing Black to reformat all included files.codeline_lengthry   rY   r?   r|   rX   fastpyiipynbpython_cell_magicsskip_source_first_lineskip_string_normalizationskip_magic_trailing_commapreviewunstableenable_unstable_featurequietverboserequired_versionincluderz   r{   force_excludern   workersr   no_cachec           -      C   sP  |  t tjdksJ dtjdd dkr td | d |r4|dur4tt| d  | d |sH|du rHtt| d	  | d |r\|s\|s\tt| d
  | d |du ret||nd\}}|| j	d< |r|rtd| d| ddd |r| 
d} tt }!||!krtd|! ddd n| tjtjfv rt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}%|r	t|}&nt }&t|&||	|
|| | ||t|t|d}'g }(|rW|
r2td  | d zt|}(W n tyV }) ztt|) | d W Y d})~)nd})~)ww |dur^d!}t||||d"}*|durvt|||%|'|*|(d# ny|dus}J zt|||||||||*|d$
}+W n ty   | d Y nw |+s|s|std% d&|v rtj tj!"  | d t#|+dkrt$|+% ||%|'|*|(|d' ndd(l&m'}, |(rtd) | d |,|+||%|'|*||d* |s|s |du r|s|*j(s|*j)rt  t|*j*r|$nd+ |du r t+j,t|*d!d, | |*j* dS )-r   )rV   	   zBlack requires Python 3.9+NrV   )rV         zPython 3.12.5 has a memory safety issue that can cause Black's AST safety checks to fail. Please upgrade to Python 3.12.6 or downgrade to Python 3.12.4rT   z3

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

One of 'SRC' or 'code' is required.z3

'--enable-unstable-feature' requires '--preview'.)NNrootzIdentified `z` as project root containing a .bluer   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   r?   rX   )target_versionsr   is_pyiis_ipynbr   string_normalizationmagic_trailing_commar   r   r   enabled_featuresz*Cannot use --line-ranges with ipynb files.T)rY   r?   r   r   )contentr   
write_backmodereportlines)
r   rm   r   r   r   rz   r{   r   r   rn   u?   No Python files are present to be formatted. Nothing to do 😴-)rm   r   r   r   r   r   r   )reformat_manyz2Cannot use --line-ranges to format multiple files.)sourcesr   r   r   r   r   r   u   All done! ✨ 🍰 ✨)rA   )-ensure_objectrs   sysversion_inforC   exitmain	get_usager   objget_parameter_sourcert   r    r   DEFAULTDEFAULT_MAPr   r   __version__splitrA   rS   rc   setr6   rK   r   rO   reformat_codeget_sourcesr   stdoutwritestdinreadlenreformat_onepopblack.concurrencyr   change_countfailure_countreturn_coder   echo)-rj   r   r   ry   rY   r?   r|   rX   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rz   r{   r   rn   r   rm   r   r   r   methodconfig_sourceuser_level_configrk   rl   	error_msgr   versionsr   r   r   r   r   r   ra   ra   rb   r      sH    
=












	





 
r   r   r   rO   c        
         C   s  t  }
|  sJ d|  |du }|du rttn|}d}t| }|D ]}|dkr?|	r?t|	}t|	|r<||d q$d}nt|}d}|sK| rt	|| |r^|r]t
d| dd	d
 q$t||  }d| }t||ru||d q$|rtt | }|jdkrt|p| dsq$|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.z/INTERNAL ERROR: `root` must be absolute but is Nr   z?--stdin-filename matches the --force-exclude regular expressionTFzSkipping invalid source: ""r   r   /z.matches the --force-exclude regular expression.ipynb)warnzFound input source: "r   zFound input source directory: ")r   r   zFound input source stdinzinvalid path: )r  is_absoluter   r   r"   r   r$   path_ignoredis_filer%   rC   r   as_posixr   suffixr(   addis_dirresolverelative_tor   r!   iterdirrA   )r   rm   r   r   r   rz   r{   r   r   rn   r   using_default_exclude	gitignoreroot_gitignorespathis_stdinroot_relative_pathra   ra   rb   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   rM   rg   format_stdin_to_stdoutr_   done	Exceptionr   	traceback	print_excfailedrt   )	r   r   r   r   r   r   r(  changedexcra   ra   rb   r  @  s   
r  )	patchable)r   r   c             
   C   s  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
}nL|rNdnt|}	|	durg|tjtjfvrg|	| sgt j}|t jurxt| ||||d	rxt j
}|	dur|tj
u r|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   )rM   rg   rt   
startswithr   r   r	  r  r   r+  r_   r   r  rS   r^   r]   
is_changedCACHEDformat_file_in_placer\   r  r,  r-  r   r.  r/  r0  )rm   r   r   r   r   r   r   r1  r)  cacher2  ra   ra   rb   r
  `  s\   




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 sDw   Y  z
t|	|||d	}W n ty]   Y d
S  tyl   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`.
    r4  Tr5  r  r6      rbNr   r   r   FzFile 'z-' cannot be parsed as valid Jupyter notebook.w)encodingnewline	rA  rB  write_through)$r  r   r	   fromtimestampstatst_mtimer
   utcopenr   readlinedecode_bytesr  format_file_contentsrN   r   r   decoderS   r_   r  r^   r]   nowr   rB   r?   r>   nullcontextioTextIOWrapperr   r  bufferr&   detach)rm   r   r   r   r<  r   thenheaderbufsrc_contentsrA  rB  dst_contentsfrO  src_namedst_namediff_contentsra   ra   rb   r:    sp   









r:  )r   r   r   c                C   sD  t tj}|du rttjj |\}}}nt	j
|v r%|dd}}}n|dd}}}|}	zz{t|| ||d}	W W tjtjj||dd}
|tjkrut	j
|v rc|	rb|	d dkrb|	d d	krb|	|7 }	n|	ro|	d dkro|	d7 }	|
|	 n1|tjtjfv rt tj}d
| }d| }t||	||}|tjkrt|}t|
}
|
| |
  dS  ty(   Y W tjtjj||dd}
|tjkrt	j
|v r|	r|	d dkr|	d d	kr|	|7 }	n|	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|
}
|
| |
  dS w tjtjj||dd}
|tjkrjt	j
|v rV|	rU|	d dkrU|	d d	krU|	|7 }	n|	rd|	d dkrd|	d7 }	|
|	 n3|tjtjfv rt tj}d
| }d| }t||	||}|tjkrt|}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-8r    r?  TrD  r   zSTDIN	zSTDOUT	F)r	   rO  r
   rI  rL  r   r  rS  r  r7   normalize_cr_newlinesrM  rQ  rR  r  rS   r_   r  r^   r]   r?   r>   r&   rT  rN   )r   r   r   r   r   rU  rm   rA  rB  dstrZ  rO  r[  r\  dra   ra   rb   r+    s   











"



r+  rX  rY  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)rX  rY  r   r   ra   ra   rb   check_stability_and_equivalence  s   
rg  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   rd  )r   format_ipynb_string
format_strrN   rg  )rX  r   r   r   rY  ra   ra   rb   rM  -  s   
rM  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   )
r-   r+   r)   SyntaxErrorrN   rj  rg  r,   r*   rstrip)
rm   r   r   src_without_trailing_semicolonhas_trailing_semicolon
masked_srcreplacements
masked_dstdst_without_trailing_semicolonrb  ra   ra   rb   format_cellI  s(   


rt  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~   rN   )ru  languagera   ra   rb   validate_metadatan  s   rz  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   r_  sourcerh  T)keependsrT   )indentensure_ascii)	rN   jsonloadsrz  r~   r   rt  
splitlinesdumps)
rX  r   r   trailing_newlinemodifiedru  cellrm   rb  rY  ra   ra   rb   ri  z  s.   
ri  c                C   sN   |rt || }|s| S 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

    rd  )rL   _format_str_oncerI   )rX  r   r   rY  ra   ra   rb   rj    s    
rj  c                   s  t j|v rt| d|\}}}t| |jd}nt|  |j}g }|jr+|j n
t|}t||d  fddt	j
t	jt	jhD }	t||| |rQt|| t||	d}
t|d} fddt	jt	jhD }d }|
|D ]}||}|| t|||dD ]
}|jt| qqp|rd	|d
 _g }|D ]	}||  q|st j|v rd|v r|S dS t| d|\}}}d|v r|S dS t j|v rd|d|S d|S )Nr^  )r   future_importsc                       h | ]	}t  |r|qS ra   r9   ru   featurer  ra   rb   r     s    z#_format_str_once.<locals>.<setcomp>)r   featuresrk  c                    r  ra   r  r  r  ra   rb   r     s    r   r   r   r_  )r7   ra  rL  encoderF   lstripr   get_future_importsdetect_target_versionsr5   PARENTHESIZED_CONTEXT_MANAGERSUNPARENTHESIZED_EXCEPT_TYPES	T_STRINGSr   rJ   r/   r1   TRAILING_COMMA_IN_CALLTRAILING_COMMA_IN_DEFvisitmaybe_empty_linesappendr0   content_linesrt   afterextend	all_linesr   r   )rX  r   r   normalized_contents_newline_typesrc_node
dst_blocksr  line_generation_featuresline_generatoreltsplit_line_featuresblockcurrent_linelinerY  normalized_contentrB  ra   r  rb   r    sr   




	







	



r  c                 C   s  t | }t|j\}}|sd|dfS tj|v rY|d dd dkr3d|d dd v r0d}n7d	}n4|d d
d dkrMd|d dd
 v rJd}nd}nd|d v rVd}nd}n|d dd dkred	nd}|d t ||}|	 ||fW  d   S 1 sw   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   r   Ns   
   r`  z
r      
)
rQ  BytesIOtokenizedetect_encodingrK  r7   ra  seekrR  r  )rm   r   srcbufrA  r   rB  tiowra   ra   rb   rL    s*   



$rL  r  noder  c          
      C   s  t  }|r|dd |D O }|  D ]]}|jtjkr"|tj q|jtjkr/|tj	 q|jtj
krL|jdurLtdd |jjD rL|tj qt|r\d|jv r[|tj q|jtjkrx|jrw|jjtjtjtjhv rw|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t,|d r|d	 jtj-kr|tj. q|jtj/kr|tj0 q|jtj1tj2hv rtdd |jD r|tj3 q|jtj4krt|jdkr|jd	 jtj5kr|tj3 q|jtj6tj7fv r|tj8 q|jtj9tj:tj;fv r|jd jtj<kr|tj= q|jtj>krpt|jd	krp|jd jtj?ks|jd jtj@krp|jd jtj?k}|r-|tjA t|j|d koL|j|d	  jtjBkoL|j|d	  jdk}	|	sp|r]|jd	 jtj@ksj|sp|jd jtj@krp|tjC 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   )r3   )ru   future_importra   ra   rb   r   O  s    z$get_features_used.<locals>.<setcomp>Nc                 s       | ]	}|j tjkV  qd S r[   )r   rP   EQUALru   childra   ra   rb   	<genexpr>]      z$get_features_used.<locals>.<genexpr>r  rT   r   rU   c                 s   r  r[   r   r=   	star_exprr  ra   ra   rb   r    r  rW   rV   r   c                 s   r  r[   r  r  ra   ra   rb   r    s    
r  as)Dr  	pre_orderr   rP   FSTRING_STARTr  r5   	F_STRINGSTSTRING_STARTr  RBRACEparentanychildrenDEBUG_F_STRINGSr;   rl   NUMERIC_UNDERSCORESSLASHr=   typedargslistarglistvarargslistPOS_ONLY_ARGUMENTS
COLONEQUALASSIGNMENT_EXPRESSIONS	decoratorr	  r<   RELAXED_DECORATORSCOMMAr  r  r:   argumentreturn_stmt
yield_exprtestlist_star_exprUNPACKING_ON_FLOW	annassignANN_ASSIGN_EXTENDED_RHS	with_stmtatomLPAR_contains_asexprRPARr  
match_stmtPATTERN_MATCHINGsubscriptlisttrailerVARIADIC_GENERICS
tname_starr  	type_stmt
typeparamsTYPE_PARAMStypevartuple	paramspectypevarr  TYPE_PARAM_DEFAULTSexcept_clauseSTARtestlistEXCEPT_STARNAMEr  )
r  r  r  nr  chargchatom_childrenis_star_excepthas_as_clausera   ra   rb   get_features_used9  s  















r  c                 C   s   | j tjkrdS | j tjkr0t| jdkr.| jd j tjkr.| jd j tjkr.t	| jd S dS | j tj
kr@tdd | jD S dS )	z-Return True if `node` contains an as-pattern.TrV   r   rU   rT   c                 s   s    | ]}t |V  qd S r[   )r  r  ra   ra   rb   r    s    z#_contains_asexpr.<locals>.<genexpr>F)r   r=   asexpr_testr  r	  r  rP   r  r  r  testlist_gexpr  )r  ra   ra   rb   r    s   r  c                   s   t | |d  fddtD S )z5Detect the version to target based on the nodes used.r  c                    s   h | ]
} t | kr|qS ra   )r4   )ru   r   r  ra   rb   r     s
    z)detect_target_versions.<locals>.<setcomp>)r  r8   )r  r  ra   r  rb   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  rZ   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)rq   rQ   r   rP   r  rl   r=   import_as_namer  import_as_namesAssertionError)r  r  	orig_nameget_imports_from_childrenra   rb   r    s   


z5get_future_imports.<locals>.get_imports_from_childrenr   rU   rT   
__future__rV   )r  rr   r.   r   rt   r  r   r=   simple_stmtrq   rQ   r	  rP   STRINGNEWLINEimport_fromrl   )r  importsr  first_childmodule_namera   r  rb   r    s2   $




r  c                   C   s   dt  dt  dt  S )NzBlack z on Python (r   )r   platformpython_implementationpython_versionra   ra   ra   rb   _black_info'  s   r  rb  c              
   C   s   zt | }W n ty } z	td| d|d}~ww zt |}W n' tyI } ztdt|j|}tdt  d| d| dd}~ww dt	|}dt	|}||krqtt
||d	d
}t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_  INTERNAL ERROR: z produced invalid code: ze. Please report a bug on https://github.com/psf/black/issues.  This invalid output might be helpful: r   rm   rb  z 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: )rG   r-  rD   r@   r   r.  	format_tb__traceback__r  rH   r?   )rm   rb  src_astr2  dst_astlogsrc_ast_strdst_ast_strra   ra   rb   re  .  sJ   
re  c                C   s^   |rdS t |||d}||kr-tt|t| |ddt||dd}tdt  d| ddS )zDRaise AssertionError if `dst` reformats differently the second time.Nrd  r}  z
first passzsecond passr  z 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: )r  r@   rt   r?   r   r  )rm   rb  r   r   newdstr  ra   ra   rb   rf  O  s"   
rf  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   rP  k  s   
rP  c                  C   s(   t tddrddlm}  |   t  d S )NfrozenFr   freeze_support)getattrr   multiprocessingr  r   r  ra   ra   rb   patched_maint  s   
r  __main__)rZ   N)rQ  r  r  r   r   r  r.  collections.abcr   r   r   r   r   
contextlibr   dataclassesr   r	   r
   enumr   json.decoderr   pathlibr   r   typingr   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%   r&   black.handle_ipynb_magicsr'   r(   r)   r*   r+   r,   r-   black.linegenr.   r/   r0   black.linesr1   r2   
black.moder3   r4   r5   r6   r7   r8   r9   black.nodesr:   r;   r<   r=   black.outputr>   r?   r@   rA   rB   rC   black.parsingrD   rE   rF   rG   rH   black.rangesrI   rJ   rK   rL   black.reportrM   rN   rO   blib2to3.pgen2rP   blib2to3.pytreerQ   rR   __file__r  COMPILEDrt   FileContentEncodingNewLinerS   FileModeContext	Parameterr   rr   r   Optiontupler   r   r   r   r   optionintChoicer   sortedIntRangeversion_optionr  r  r  pass_contextri   r   r  r  r  r
  rg   r:  r+  rg  rM  rt  rz  ri  rj  r  bytesrL  r  r  r  r  r  re  rf  rP  r  rd   ra   ra   ra   rb   <module>   s*   0$	 
A








				

	

		




J Z



	

i
 	A
G
?

%!
0
 M$

 #


2"

