B
    ÔùÓ`º3  ã               @   sZ  d 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 e ¡ d pVd ¡ Zy,ejejjed�e_ejejjed�e_W n ek
rœ   Y nX dZedddddde	jdddddddd	�Zd
ZdZdZdZd'dd„Zd(dd„Zdd„ Zdd„ Zdd„ Z dd„ Z!dd„ Z"d)dd„Z#d*dd„Z$d d!„ Z%d"d#„ Z&d+d$d%„Z'e(d&k�rVe'ej)ƒ dS ),z#CLI frontend module for anyconfig.
é    Né   )ÚapiÚparserÚutilszUTF-8)Úencodinga!  %(prog)s [Options...] CONF_PATH_OR_PATTERN_0 [CONF_PATH_OR_PATTERN_1 ..]

Examples:
  %(prog)s --list  # -> Supported config types: configobj, ini, json, ...
  # Merge and/or convert input config to output config [file]
  %(prog)s -I yaml -O yaml /etc/xyz/conf.d/a.conf
  %(prog)s -I yaml '/etc/xyz/conf.d/*.conf' -o xyz.conf --otype json
  %(prog)s '/etc/xyz/conf.d/*.json' -o xyz.yml \
    --atype json -A '{"obsoletes": "syscnf", "conflicts": "syscnf-old"}'
  %(prog)s '/etc/xyz/conf.d/*.json' -o xyz.yml \
    -A obsoletes:syscnf;conflicts:syscnf-old
  %(prog)s /etc/foo.json /etc/foo/conf.d/x.json /etc/foo/conf.d/y.json
  %(prog)s '/etc/foo.d/*.json' -M noreplace
  # Query/Get/set part of input config
  %(prog)s '/etc/foo.d/*.json' --query 'locs[?state == 'T'].name | sort(@)'
  %(prog)s '/etc/foo.d/*.json' --get a.b.c
  %(prog)s '/etc/foo.d/*.json' --set a.b.c=1
  # Validate with JSON schema or generate JSON schema:
  %(prog)s --validate -S foo.conf.schema.yml '/etc/foo.d/*.xml'
  %(prog)s --gen-schema '/etc/foo.d/*.xml' -o foo.conf.schema.ymlF)ÚloglevelÚlistÚoutputÚitypeÚotypeZatypeÚmergeÚignore_missingÚtemplateÚenvÚschemaÚvalidateÚ
gen_schemaÚ
extra_optsa5  Explicitly select type of argument to provide configs from %s.

If this option is not set, original parser is used: 'K:V' will become {K: V},
'K:V_0,V_1,..' will become {K: [V_0, V_1, ...]}, and 'K_0:V_0;K_1:V_1' will
become {K_0: V_0, K_1: V_1} (where the tyep of K is str, type of V is one of
Int, str, etc.a&  Query with JMESPath expression language. See http://jmespath.org for more about JMESPath expression. This option is not used with --get option at the same time. Please note that python module to support JMESPath expression (https://pypi.python.org/pypi/jmespath/) is required to use this optionaa  Specify key path to get part of config, for example, '--get a.b.c' to config {'a': {'b': {'c': 0, 'd': 1}}} gives 0 and '--get a.b' to the same config gives {'c': 0, 'd': 1}. Path expression can be JSON Pointer expression (http://tools.ietf.org/html/rfc6901) such like '', '/a~1b', '/m~0n'. This option is not used with --query option at the same time. zžSpecify key path to set (update) part of config, for example, '--set a.b.c=1' to a config {'a': {'b': {'c': 0, 'd': 1}}} gives {'a': {'b': {'c': 1, 'd': 1}}}.c             C   sú  | dkrt } t ¡ }d |¡}d| d }tj}d |¡}d| d|   }tjtd�}|jf | Ž |j	dt
d	d
d� |j	dddt ¡  d� | d¡}|j	ddddd� | d¡}	|	j	dddd� |	j	dddd� | d¡}
|
j	ddtd� |
j	dtd� |
j	d td� |j	d!d"d#d� |j	d$d%|d&|d' d(� |j	d)d*|d+|d, d(� |j	d-d.|d/|d(� |j	d0d1d2d� |j	d3|d4t| d(� | d5¡}|j	d6d7dd8d� |j	d9d:dd;d� |j	d<d=dd>d� |j	d?d@dAd� |j	dBdCdDd� |j	dEdFdGdHdIdJ� |S )Kz0
    :param defaults: Default option values
    Nz, z$Select type of %s config files from z% [Automatically detected by file ext]z/Select strategy to merge multiple configs from z [%(merge)s])ÚusageÚinputsÚ*zInput files)ÚtypeÚnargsÚhelpz	--versionÚversionz%%(prog)s %s)Úactionr   zList specific optionsz-Lz--listÚ
store_truezList supported config types)r   r   zSchema specific optionsz
--validatezbOnly validate input files and do not output. You must specify schema file with -S/--schema option.z--gen-schemaz^Generate JSON schema for givne config file[s] and output it instead of (merged) configuration.zQuery/Get/set optionsz-Qz--query)r   z--getz--setz-oz--outputzOutput file pathz-Iz--itypeZITYPEZInput)ÚchoicesÚmetavarr   z-Oz--otypeZOTYPEZOutputz-Mz--mergeZMERGEz-Az--argszArgument configs to overridez--atypeZATYPEzCommon optionsz-xz--ignore-missingzIgnore missing input filesz-Tz
--templatezEnable template config supportz-Ez--envz3Load configuration defaults from environment valuesz-Sz--schemazSpecify Schema file[s] pathz-ez--extra-optsz‚Extra options given to the API call, --extra-options indent:2 (specify the indent for pretty-printing of JSON outputs) for examplez-vz	--verboseÚcountr   z&Verbose mode; -v or -vv (more verbose))r   Údestr   )ÚDEFAULTSÚAPIÚ
list_typesÚjoinZMERGE_STRATEGIESÚargparseÚArgumentParserÚUSAGEÚset_defaultsÚadd_argumentÚstrr   Úadd_argument_groupÚ_QUERY_HELPÚ	_GET_HELPÚ	_SET_HELPÚ_ATYPE_HELP_FMT)ÚdefaultsÚctypesZctypes_sZ	type_helpZmtsZmts_sZmt_helpÚapsrZlpogZspogZgspogZcpog© r3   ú1/tmp/pip-unpacked-wheel-bpftjxoo/anyconfig/cli.pyÚmake_parserR   s`    










r5   c             C   s.   |dkrt jnt j | tj ¡ t  |¡ dS )z€
    Exit the program with printing out messages.

    :param content: content to print out
    :param exit_code: Exit code
    r   N)ÚsysÚstdoutÚstderrÚwriteÚosÚlinesepÚexit)ÚcontentZ	exit_coder3   r3   r4   Ú_exit_with_outputš   s     r>   c              C   sp   t j} dd t ¡ ¡ }dd dd„ t ¡ D ƒ¡ }dd„ t ¡ D ƒ}d|  |  |¡ }t|  |||g¡ƒ d	S )
z+Show list of info of parsers available
    zSupported types: z, zIDs: c             s   s   | ]\}}|V  qd S )Nr3   )Ú.0ÚcZ_psr3   r3   r4   ú	<genexpr>«   s    z_show_psrs.<locals>.<genexpr>c             S   s,   g | ]$\}}d |d  dd„ |D ƒ¡f ‘qS )z  %s: %sz, c             s   s   | ]}|  ¡ V  qd S )N)Zcid)r?   Úpr3   r3   r4   rA   ­   s    z(_show_psrs.<locals>.<listcomp>.<genexpr>)r$   )r?   ÚxZpsr3   r3   r4   ú
<listcomp>­   s   z_show_psrs.<locals>.<listcomp>zFile extensions:N)r:   r;   r$   r"   r#   Zlist_by_cidZlist_by_extensionr>   )ÚsepÚtypesZcidsZx_vs_psÚextsr3   r3   r4   Ú
_show_psrs¥   s    rH   c             C   sž   t ƒ }| | ¡}|jr t d¡ |jr:d|jkr€tj|_nF|jrHt	ƒ  n8|j
rntj ¡ }t||ƒ t d¡ n| ¡  t d¡ |jrš|jdkrštddƒ |S )zÃ
    Show supported config format types or usage.

    :param argv: Argument list to parse or None (sys.argv will be set).
    :return: argparse.Namespace object or None (exit before return)
    Úalwaysú-r   r   Nz*--validate option requires --scheme option)r5   Ú
parse_argsr   ÚwarningsÚsimplefilterr   r6   Ústdinr   rH   r   r:   ÚenvironÚcopyÚ_output_resultr<   Úprint_usager   r   r>   )Úargvr2   ÚargsÚcnfr3   r3   r4   Ú_parse_args´   s$    







rV   c             C   s   | dkrt |dƒ dS )z€
    :param cnf: Loaded configuration object or None indicates load failure
    :param msg: Message to print out if failure
    Nr   )r>   )rU   Úmsgr3   r3   r4   Ú_exit_if_load_failureÔ   s    rX   c             C   s*   t  | |¡\} }| dkr&td| dƒ | S )z¡
    :param cnf: Configuration object to print out
    :param get_path: key path given in --get option
    :return: updated Configuration object if no error
    NzFailed to get result: err=%sr   )r"   Úgetr>   )rU   Úget_pathÚerrr3   r3   r4   Ú_do_getÝ   s    r\   c          	   C   sz   d}|dkrryt  | d ¡ ¡ }W qv t jk
rN   t|| d  | dƒ Y qv ttfk
rn   t|dƒ Y qvX n|}|S )z¶
    :param inpaths: List of input file paths
    :param itype: Input type or None
    :param fmsg: message if it cannot detect otype by 'inpath'
    :return: Output type :: str
    zUSpecify inpath and/or outpath type[s] with -I/--itype or -O/--otype option explicitlyNr   r   )r"   Úfindr   ÚUnknownFileTypeErrorr>   Ú
ValueErrorÚ
IndexError)Úinpathsr
   ÚfmsgrW   r   r3   r3   r4   Ú_output_type_by_input_pathê   s    rc   c             C   sn   |dkri }yt j| ||f|Ž W nF t jk
rF   t|| dƒ Y n$ t jk
rh   td| dƒ Y nX dS )a  
    :param cnf: Configuration object to print out
    :param outpath: Output file path or None
    :param otype: Output type or None
    :param fmsg: message if it cannot detect otype by 'inpath'
    :param extra_opts: Map object will be given to API.dump as extra options
    Nr   zInvalid output type '%s')r"   Údumpr^   r>   ÚUnknownProcessorTypeError)rU   Úoutpathr   rb   r   r3   r3   r4   Ú	_try_dump   s    rg   c             C   sj   d}|j |jpd }}t | ¡s,tt| ƒƒ |r8|dkrTtj}|dkrTt||j	|ƒ}t
| ||||d� dS )zå
    :param cnf: Configuration object to print out
    :param args: :class:`argparse.Namespace` object
    :param inpaths: List of input file paths
    :param extra_opts: Map object will be given to API.dump as extra options
    zOUknown file type and cannot detect appropriate backend from its extension, '%s'ÚjsonrJ   N)r   )r	   r   r   Zis_dict_liker>   r*   r6   r7   rc   r
   rg   )rU   rT   ra   r   rb   rf   r   r3   r3   r4   rQ     s    
rQ   c          	   C   s    y.t j| j| jf| j| j| j| jdœ|—Ž}W nV t jk
rT   t	d| j dƒ Y n2 t j
k
r„   t	d| jd | j¡f dƒ Y nX t|dd | j¡ ƒ |S )z~
    :param args: :class:`argparse.Namespace` object
    :param extra_opts: Map object given to API.load as extra options
    )Zac_ignore_missingZac_mergeZac_templateZ	ac_schemazWrong input type '%s'r   zDNo appropriate backend was found for given file type='%s', inputs=%sz, zFailed to load: args=%s)r"   Úloadr   r
   r   r   r   r   re   r>   r^   r$   rX   )rT   r   Údiffr3   r3   r4   Ú
_load_diff(  s"    rk   c             C   sX   |j rt | |j ¡} n>|jr*t| |jƒ} n*|jrT|j d¡\}}t | |t 	|¡¡ | S )z˜
    :param cnf: Mapping object represents configuration data
    :param args: :class:`argparse.Namespace` object
    :return: 'cnf' may be updated
    ú=)
Úqueryr"   Z	try_queryrY   r\   ÚsetÚsplitÚset_r   Úparse)rU   rT   ÚkeyÚvalr3   r3   r4   Ú
_do_filterA  s    rt   c             C   sÂ   t | r
| ntjdd… ƒ}|jr*tj ¡ ni }tƒ }|jrFt	 
|j¡}t||ƒ}|rbt ||¡ n|}|jr„t	 
|j¡}t ||¡ |jr’tdƒ |jr¢t |¡nt||ƒ}t|||j|d� dS )zM
    :param argv: Argument list to parse or None (sys.argv will be set).
    r   NzValidation succeeds)r   )rV   r6   rS   r   r:   rO   rP   Údictr   r   rq   rk   r"   r   rT   r   r>   r   rt   rQ   r   )rS   rT   rU   r   rj   r3   r3   r4   ÚmainR  s     
rv   Ú__main__)N)r   )N)NN)N)*Ú__doc__r%   ÚioÚlocaler:   r6   rL   Ú r   r"   r   r   ÚgetdefaultlocaleÚlowerZ	_ENCODINGÚTextIOWrapperr7   Úbufferr8   ÚAttributeErrorr'   ru   ZMS_DICTSr!   r/   r,   r-   r.   r5   r>   rH   rV   rX   r\   rc   rg   rQ   rk   rt   rv   Ú__name__rS   r3   r3   r3   r4   Ú<module>   sJ   
	
H
 	



