U
    i.                     @  s   d dl mZ d dlZd dlZd dlZd dlm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 d dlmZ d dlmZ d d	lmZ dddddddZG dd dZddddddZedkre  dS )    )annotationsN)dumps)abspathbasenamedirnamejoinrealpath)python_version)unidata_version)from_fp)CliDetectionResult)__version__yesstrbool)questiondefaultreturnc                 C  sV   |dkrdnd}t | |   }|s0|dkS |dkr<dS |dkrHdS td qd	S )
zBAsk a yes/no question via input() and return the answer as a bool.r   z [Y/n] z [y/N] )yr   T)nnoFzPlease respond with 'y' or 'n'.N)inputstriplowerprint)r   r   promptchoice r   C/tmp/pip-unpacked-wheel-mwc9rwws/charset_normalizer/cli/__main__.pyquery_yes_no   s    r   c                   @  sD   e Zd ZdZddddddd	d
ZdddddZddddZdS )FileTypea  Factory for creating file object types

    Instances of FileType are typically passed as type= arguments to the
    ArgumentParser add_argument() method.

    Keyword Arguments:
        - mode -- A string indicating how the file is to be opened. Accepts the
            same values as the builtin open() function.
        - bufsize -- The file's desired buffer size. Accepts the same values as
            the builtin open() function.
        - encoding -- The file's encoding. Accepts the same values as the
            builtin open() function.
        - errors -- A string indicating how encoding and decoding errors are to
            be handled. Accepts the same value as the builtin open() function.

    Backported from CPython 3.12
    rNr   intz
str | None)modebufsizeencodingerrorsc                 C  s   || _ || _|| _|| _d S N)_mode_bufsize	_encoding_errors)selfr$   r%   r&   r'   r   r   r   __init__3   s    zFileType.__init__z	typing.IO)stringr   c              
     s   |dkrld j kr*d j kr$tjjS tjS t fdddD rXd j krRtjjS tjS d j  }t|zt| j  j j	 j
W S  tk
r } zd| d	| }t|W 5 d }~X Y nX d S )
N-r!   bc                 3  s   | ]}| j kV  qd S r(   )r)   ).0cr-   r   r   	<genexpr>D   s     z$FileType.__call__.<locals>.<genexpr>Zwaxzargument "-" with mode zcan't open 'z': )r)   sysstdinbufferanystdout
ValueErroropenr*   r+   r,   OSErrorargparseArgumentTypeError)r-   r/   msgemessager   r4   r   __call__?   s    
zFileType.__call__)r   c                 C  sX   | j | jf}d| jfd| jfg}ddd |D dd |D  }t| j d| dS )	Nr&   r'   , c                 S  s   g | ]}|d krt |qS )r"   )repr)r2   argr   r   r   
<listcomp>U   s      z%FileType.__repr__.<locals>.<listcomp>c                 S  s&   g | ]\}}|d k	r| d|qS )N=r   )r2   kwrF   r   r   r   rG   V   s      ())r)   r*   r+   r,   r   type__name__)r-   argskwargsargs_strr   r   r   __repr__Q   s    zFileType.__repr__)r!   r"   NN)rM   
__module____qualname____doc__r.   rC   rQ   r   r   r   r   r        s       r    zlist[str] | Noner#   )argvr   c                   s,  t jdd}|jdtdddd |jdd	d
dddd |jddd
dddd |jddd
dddd |jddd
dddd |jddd
dddd |jdd d
dd!d"d |jd#d$d
dd%d&d |jd'd(d)d*td+d,d- |jd.d/d0tt tt	j
 d1rd2nd3d4d5 || }|jd6krZ|jdkrZ|jrH|jD ]  q8td7tjd8 d9S |jd6kr|jdkr|jr|jD ]  qtd:tjd8 d9S |jd;k s|jd<kr|jr|jD ]  qtd=tjd8 d9S g }|jD ]ĉt|j|j|jdkd>}|   d?krztd@j|jd<k r@dAndBtjd8 |ttjd?g g dCg dd<d;d?d6 n*ttj j j  fdDdE j!D  j" j# j$ j% j&d?d6}|| t'|d9kr6|j(r6|D ]V kr|ttjjj fdFdEj!D j"j#j$j%j&d?d q|jd6kr j)dGd6krtdHjtjd8 j*dkr  qt+t,j}t-t,j}|.dI}|jdkr|/dJ j j*dkr  n<|jdkrt0dKjdLdkrj*dkr  qz<t1|dI1||_2t3|j2dM}	|	4 5  W 5 Q R X W nR t6k
r }
 z2tt7|
tjd8 j*dkr  W Y  dNS d?}
~
X Y nX j*dkr  q|j8dkrtt9t'|d9krdOdE |D n|dP j:d6dQdR n*|jD ]"tdS1fdTdE|D  qdPS )Uz
    CLI assistant using ARGV and ArgumentParser
    :param argv:
    :return: 0 if everything is fine, anything else equal trouble
    zvThe Real First Universal Charset Detector. Discover originating encoding used on text file. Normalize text to unicode.)descriptionfilesrb+zFile(s) to be analysed)rL   nargshelpz-vz	--verbose
store_trueFverbosezjDisplay complementary information about file if any. Stdout will contain logs about the detection process.)actionr   destr[   z-az--with-alternativealternativeszIOutput complementary possibilities if any. Top-level JSON WILL be a list.z-nz--normalize	normalizezLPermit to normalize input file. If not set, program does not write anything.z-mz	--minimalminimalzBOnly output the charset detected to STDOUT. Disabling JSON output.z-rz	--replacereplacezGReplace file when trying to normalize it instead of creating a new one.z-fz--forceforcezHReplace file without asking if you are sure, use this flag with caution.z-iz--no-preemptiveno_preemptivez>Disable looking at a charset declaration to hint the detector.z-tz--thresholdstoreg?	thresholdzUDefine a custom maximum amount of noise allowed in decoded content. 0. <= noise <= 1.)r^   r   rL   r_   r[   z	--versionversionz;Charset-Normalizer {} - Python {} - Unicode {} - SpeedUp {}z.pyZOFFONz"Show version information and exit.)r^   rh   r[   Tz.Use --replace in addition of --normalize only.)file   z*Use --force in addition of --replace only.g        g      ?z---threshold VALUE should be between 0. AND 1.)rg   explainZpreemptive_behaviourNz4Unable to identify originating encoding for "{}". {}z-Maybe try increasing maximum amount of chaos. Unknownc                   s   g | ]}| j kr|qS r   r&   r2   cp)
best_guessr   r   rG      s   
zcli_detect.<locals>.<listcomp>c                   s   g | ]}| j kr|qS r   ro   rp   )elr   r   rG     s   
utfzJ"{}" file does not need to be normalized, as it already came from unicode..r"   z0Are you sure to normalize "{}" by replacing it ?r   wb   c                 S  s   g | ]
}|j qS r   )__dict__r2   rs   r   r   r   rG   U  s     r      )ensure_asciiindentrD   c                   s&   g | ]}|j t jkr|jp d qS )Z	undefined)pathr   namer&   ry   )my_filer   r   rG   ^  s   );r>   ArgumentParseradd_argumentr    floatformatr   r	   r
   	md_module__file__r   endswith
parse_argsrc   ra   rW   closer   r6   stderrrd   rg   r   r]   re   bestr~   appendr   r   r&   Zencoding_aliasesZcould_be_from_charsetlanguageZ	alphabetsbomZpercent_chaosZpercent_coherencelenr`   
startswithclosedr   r   r   splitinsertr   r   Zunicode_pathr<   writeoutputr=   r   rb   r   rx   )rU   parserrN   Zx_matchesZ
cli_resultZdir_path	file_nameZo_fprA   r   )rr   rs   r   r   
cli_detect[   s      		











$


r   __main__)r   )N)
__future__r   r>   r6   typingjsonr   os.pathr   r   r   r   r   platformr	   unicodedatar
   Zcharset_normalizer.mdZmdr   Zcharset_normalizerr   Zcharset_normalizer.modelsr   Zcharset_normalizer.versionr   r   r    r   rM   r   r   r   r   <module>   s$   ;  