
    ~2                         S r SSKJr  SSKJr  SSKJr  / SQrSSKrSSKrSSKrSSK	r	SSK
r
SSKJr  Sr " S	 S
\5      r " S S\5      r\" \5      rS rS r\S:X  a  \" 5         gg)a  A mechanism for library configuration.

Whenever App Engine library code needs a user-configurable value, it should use
the following protocol:
    1. Pick a prefix unique to the library module, for example: `mylib`.
    2. Call `lib_config.register(prefix, mapping)` with that prefix as the first
       argument and a dict mapping suffixes to default functions as the second.
    3. The `register()` function returns a configuration handle that is unique
       to this prefix. The configuration handle object has attributes that
       correspond to each of the suffixes given in the mapping. Call these
       functions to access the user's configuration value.  If the user didn't
       configure a function, the default function from the mapping is called
       instead.
    4. Document the function name and its signature and semantics.

Users that want to provide configuration values should create a module named
`appengine_config.py` in the top-level directory of their application and define
functions as documented by various App Engine library components in that module.
To change the configuration, edit the file and re-deploy the application. When
using the SDK, no redeployment is required; the development server will pick up
the changes the next time it handles a request.

Third party libraries can also use this mechanism. For casual use, calling the
`register()` method with a unique prefix is acceptable. For more complex
libraries, however, you should instantiate a new `LibConfigRegistry` instance
that uses a different module name.


Example `appengine_config.py` file::

    from somewhere import MyMiddleWareClass

    def mylib_add_middleware(app):
      app = MyMiddleWareClass(app)
      return app


Example library use::

    from google.appengine.api import lib_config

    config_handle = lib_config.register(
        'mylib',
        {'add_middleware': lambda app: app})

    def add_middleware(app):
      return config_handle.add_middleware(app)
    )absolute_import)print_function)unicode_literals)DEFAULT_MODNAMELibConfigRegistryConfigHandleregistermainN)encodingappengine_configc                   V    \ rS rSrSrS rS r\R                  4S jr	S r
S rS rS	rg
)r   ]   z3A registry containing library configuration values.c                 `    Xl         0 U l        SU l        [        R                  " 5       U l        g)zConstructor.

Args:
  modname: The module name to be imported.

Note: the actual import of this module is deferred until the first
time a configuration value is requested through attribute access
on a ConfigHandle instance.
N)_modname_registrations_module	threadingRLock_lock)selfmodnames     .lib/googlecloudsdk/appengine/api/lib_config.py__init__LibConfigRegistry.__init__`   s&     MDDL"DJ    c                 t   UR                  S5      (       d  US-  nU R                  R                  5          U R                  R	                  U5      nUc  [        X5      nX0R                  U'   U R                  R                  5         UR                  U5        U$ ! U R                  R                  5         f = f)a  Registers a set of configuration names.

Args:
  prefix: A shared prefix for the configuration names being registered.
      If the prefix doesn't end in `_`, that character is appended.
  mapping: A dict that maps suffix strings to default values.

Returns:
  A `ConfigHandle` instance.

You can re-register the same prefix: the mappings are merged, and for
duplicate suffixes, the most recent registration is used.
_)endswithr   acquirer   getr   release_update_defaults)r   prefixmappinghandles       r   r	   LibConfigRegistry.registero   s     ??3mfJJ""&&v.f	f+&,F#
jj
G$M jjs   7B B7c                    U R                   R                  5          U R                  bR  U R                  [        R                  R                  U R                  5      L a   U R                   R                  5         g U" U R                  5        [        R                  U R                     U l        U R                   R                  5         g! [         a  n[        U5      SR                  U R                  5      SR                  U R                  5      4;  a  e [        5       U l        U R                  [        R                  U R                  '    SnANSnAff = f! U R                   R                  5         f = f)a  Tries to import the configuration module if it is not already imported.

This function always sets `self._module` to a value that is not `None`;
either the imported module (if it was imported successfully) or a placeholder
`object()` instance (if an `ImportError` was raised) is used. Other
exceptions are not caught.

When a placeholder instance is used, the instance is also put in `sys.modules`.
This usage allows us to detect when `sys.modules` was changed (as
`dev_appserver.py` does when it notices source code changes) and retries the
`import_module` in that case, while skipping it (for speed) if nothing has
changed.

Args:
  import_func: Used for dependency injection.
NzNo module named {}z(import of {} halted; None in sys.modules)r   r   r   sysmodulesr    r   r!   ImportErrorstrformatobject)r   import_funcerrs      r   
initializeLibConfigRegistry.initialize   s   " 	JJ
,,
"
,,#++//$--8
8 jj2DMM" {{4==1
jj  2s8 ''66==dmmLN N x%)\\DMM"2 jjs7   AE <C "E 
EA:EE EE E8c                    U R                   R                  5          U R                  c   U R                   R                  5         gSU l        [	        U R
                  R                  5       5      nU R                   R                  5         U H  nUR                  5         M     g! U R                   R                  5         f = f)zDrops the imported configuration module.

If the configuration module has not been imported, no operation occurs, and
the next operation takes place.
N)r   r   r   r!   listr   values_clear_cache)r   handlesr%   s      r   resetLibConfigRegistry.reset   s     	JJ		
 jj dlT((//12g
jj  jjs   B# *B# #B?c              #     #    U R                   R                  5          [        U R                  SS5      nU(       d   U R                   R	                  5         g[        UR                  5       5      nU R                   R	                  5         [        U5      nU H%  u  pVUR                  U5      (       d  M  XTS U4v   M'     g! U R                   R	                  5         f = f7f)a  Generates `(key, value)` pairs from the config module matching prefix.

Args:
  prefix: A prefix string ending in `_`, for example: `mylib_`.

Yields:
  `(key, value)` pairs, where `key` is the configuration name with the
  prefix removed, and `value` is the corresponding value.
__dict__N)	r   r   getattrr   r!   r3   itemslen
startswith)r   r#   r$   r<   nskipkeyvalues          r   _pairsLibConfigRegistry._pairs   s      	JJj$7g jj 7==?#e
jjKE
			&k5    jjs.   C!C C!C 1A C!5C!CC!c                 `   U R                  5         / nU R                  R                  5          [        U R                  S5      (       d  [        SU R                  -  5        OpU R                  (       d  [        SU R                  -  5        OF[        SU R                  -  5        [        S5        [        U R                  R                  5       5      nU R                  R                  5         [        U5       H  u  p#UR                  5         M     g! U R                  R                  5         f = f)z5Prints information about all registrations to stdout.r:   zModule %s.py does not exist.zNo registrations for %s.py.zRegistrations in %s.py:(----------------------------------------N)r0   r   r   hasattrr   printr   r   r3   r<   r!   sorted_dump)r   r6   r   r%   s       r   rI   LibConfigRegistry._dump   s    OOGJJ
T\\:..,t}}<=""+dmm;<'$--78ft**0023
jjG_	lln % jjs   B$D D-)r   r   r   r   N)__name__
__module____qualname____firstlineno____doc__r   r	   	importlibimport_moduler0   r7   rB   rI   __static_attributes__ r   r   r   r   ]   s/    ;#6 $-#:#: #J&!.r   r   c                   @    \ rS rSrSrSrS rS rS rS r	S r
S	 rS
rg)r      zA set of configuration for a single library module or package.

Public attributes of instances of this class are configuration values.
Attributes are dynamically computed (in `__getattr__()`) and cached as regular
instance attributes.
Fc                     UR                  S5      (       d   eXl        0 U l        0 U l        X l        [
        R                  " 5       U l        g)zConstructor.

Args:
  prefix: A shared prefix for the configuration names being registered. It
      must end in `_`. This requirement is enforced by
      `LibConfigRegistry`.
  registry: A `LibConfigRegistry` instance.
r   N)r   _prefix	_defaults
_overrides	_registryr   r   r   )r   r#   registrys      r   r   ConfigHandle.__init__   s?     ??3LDNDON"DJr   c                    U R                   R                  5          UR                  5        HA  u  p#UR                  S5      (       a  UR	                  S5      (       a  M3  X0R
                  U'   MC     U R                  (       a  U R                  5         U R                   R                  5         g! U R                   R                  5         f = f)zaUpdates the default mappings.

Args:
  mapping: A dict mapping suffix strings to default values.
__N)	r   r   r<   r>   r   rX   _initialized_update_configsr!   )r   r$   r@   rA   s       r   r"   ConfigHandle._update_defaults  s     	JJ*#>>$CLL$6$6
#s ( 
		
jjdjjs   A6B- -C	c                    U R                   R                  5          U R                  (       a  U R                  5         U R                  R                  5         U R                  R                  U R                  5       HH  u  pXR                  ;  a&  [        R                  " SU R                  U-   5        M:  X R                  U'   MJ     SU l        U R                   R                  5         g! U R                   R                  5         f = f)zUpdates the configuration values.

This clears the cached values, initializes the registry, and loads
the configuration values from the config module.
z!Configuration "%s" not recognizedTN)r   r   r_   r5   rZ   r0   rB   rW   rX   loggingwarnrY   r!   )r   r@   rA   s      r   r`   ConfigHandle._update_configs  s     	JJ			
nn!--dll;*#nn$
,,:DLL3<N
O!&//#
	 <
 d
jjdjjs   B3C* *Dc                 R   U R                   R                  5          SU l        U R                   H+  nU R                  R                  US5         [        X5        M-     U R                   R                  5         g! [         a     MW  f = f! U R                   R                  5         f = f)zClears the cached values.FN)	r   r   r_   rX   rY   popdelattrAttributeErrorr!   r   r@   s     r   r5   ConfigHandle._clear_cache,  s    JJ	d#C&	
$
   jj  	
	 jjs/   2B
 A9B
 9
BB
 BB
 
B&c                    U R                   R                  5          [        SU R                  -  5        U R                  (       aH  [        S5        [        U R                  5       H#  n[        SU< SU R                  U   < 35        M%     O[        S5        U R                  (       aH  [        S5        [        U R                  5       H#  n[        SU< SU R                  U   < 35        M%     O[        S5        [        S5        U R                   R                  5         g	! U R                   R                  5         f = f)
z=Prints information about this set of registrations to stdout.z
Prefix %s:z  Overrides:z    z = z  No overridesz  Defaults:z  No defaultsrE   N)r   r   rG   rW   rY   rH   rX   r!   rj   s     r   rI   ConfigHandle._dump:  s    JJL4<<'(	n$//*C
dooc&:;
< + 		m$..)C
dnnS&9:
; * 	oFm
jjdjjs   C+D" "D>c                    U R                   R                  5          U R                  (       d  U R                  5         XR                  ;   a  U R                  U   nO*XR
                  ;   a  U R
                  U   nO[        U5      e[        XU5        UU R                   R                  5         $ ! U R                   R                  5         f = f)aF  Dynamic attribute access.

Args:
  suffix: The attribute name.

Returns:
  A configuration values.

Raises:
  AttributeError: If the suffix is not a registered suffix.

The first time an attribute is referenced, this method is invoked. The value
returned is taken either from the config module or from the registered
default.
)	r   r   r_   r`   rY   rX   ri   setattrr!   )r   suffixrA   s      r   __getattr__ConfigHandle.__getattr__O  s      	JJ	??	"'^^#v&V$$dE"
jjdjjs   A7B. .C
)rX   r_   r   rY   rW   rZ   N)rK   rL   rM   rN   rO   r_   r   r"   r`   r5   rI   rq   rR   rS   r   r   r   r      s,     ,# "(*r   r   c                 ,    [         R                  X5      $ )a7  Register a set of configurations with the default config module.

Args:
  prefix: A shared prefix for the configuration names being registered.
      If the prefix doesn't end in `_`, that character is appended.
  mapping: A dict mapping suffix strings to default values.

Returns:
  A `ConfigHandle` instance.
)_default_registryr	   )r#   r$   s     r   r	   r	   t  s     
	#	#F	44r   c            
         [         R                  " [        R                  SS5      R	                  S5      (       d  SSKJn   U R                  5       (       d}  U R                  5       cK  [        S5        [        SU R                  [         R                  " [        R                  S	S5      5      5        g[        S
5        [        5         [        S5        g[        S5        [        5         [        R                  5         g)a7  Dumps the configuration, using a CGI-style request handler.

Put this in your `app.yaml` file to enable (you can pick any URL)::

    - url: /lib_config
      script: $PYTHON_LIB/google/appengine/api/lib_config.py


Note:
    Unless you are using the SDK, you must be an administrator to use this
    function.
SERVER_SOFTWARE Devr   usersNzStatus: 302z	Location:	PATH_INFOzStatus: 403	ForbiddenzContent-type: text/plain)r   GetEncodedValueosenvironr>   googlecloudsdk.appengine.apirz   is_current_user_adminget_current_userrG   create_login_urlrt   rI   ry   s    r   r
   r
     s     
	!	!"**"3R
99CE9J
K2&&((				!	)mk511(2J2JJJR3) * 	+  	mk"#'r   __main__)rO   
__future__r   r   r   __all__rP   rc   r~   r(   r   googlecloudsdk.core.utilr   r   r-   r   r   rt   r	   r
   rK   rS   r   r   <module>r      s    /b ' % '   	 
  - %M M`@6 @H &o6 5B z& r   