ó
âdc           @` s…   d  Z  d d l m Z m Z m Z m Z d d l Td d l Z d d l Z d d l	 Z	 d d l
 Z
 d g Z d e f d „  ƒ  YZ d S(   uL   Class providing a string template to substitute fields and their arguments.
i    (   t   absolute_importt   divisiont   print_functiont   unicode_literals(   t   *Nu   StringPatternt   StringPatternc           B` sÔ   e  Z d  Z d d „ Z e d „  ƒ Z e d „  ƒ Z e d „  ƒ Z d „  Z	 e
 d „  ƒ Z e
 d „  ƒ Z e d „  ƒ Z e
 d d	 „ ƒ Z e
 d
 „  ƒ Z e
 d „  ƒ Z e d „  ƒ Z e d „  ƒ Z d „  Z RS(   uD  
  This class provides string substitution based on fields and their arguments.
  
  Fields are enclosed in square brackets (such as `"[field]"`). Field arguments
  are separated by commas (`","`). The number of arguments depends on the
  substitution function in the `fields` dictionary passed to `__init__`.
  
  To insert literal commas in field arguments, enclose the arguments in square
  brackets. To insert square brackets in field arguments, enclose the arguments
  in square brackets and double the square brackets (the ones inside the
  argument, not the enclosing ones). If the last argument is enclosed in square
  brackets, insert a comma after the argument.
  
  Attributes:
  
  * `pattern` - The original string pattern.
  
  * `pattern_parts` - Parts of `pattern` split into strings (parts of the
    pattern not containing the field) and fields (tuples describing the field).
  
  * `parsed_fields_and_matching_regexes` - Dictionary of
    `(parsed field, first matching field regular expression)` pairs.
  
  Examples:
  
  Suppose `fields` contains a field named `"date"` returning the current date
  (requiring a date format as a parameter).
  
  * "image" -> "image", "image", ...
  * "image_[date, %Y-%m-%d]" -> "image_2016-07-16", ...
  * "[[image]]" -> "[image]", ...
  * "[date, [[[%Y,%m,%d]]] ]" -> "[2016,07,16]", ...
  c         C` sX   | |  _  t j | d k	 r! | n g  ƒ |  _ |  j |  j  |  j ƒ \ |  _ } |  _ d S(   u«  
    Parameters:
    
    * `pattern` - String containing fields to substitute.
    
    * `fields` - List of `(field regex, function)` tuples. `field regex` matches
      the fields in the pattern and `function` substitutes the field with the
      value returned by the function. The function must always specify at least
      one argument - the field to be substituted.
      
      Any unmatched fields will be silently ignored.
      
      Fields in the pattern are enclosed in square brackets (`"[field]"`). To
      insert literal square brackets, double the characters (`"[["`, `"]]"`).
      
      If `fields` is `None`, no fields in the pattern will be substituted.
    N(   t   _patternt   collectionst   OrderedDictt   Nonet   _fieldst   parse_patternt   _pattern_partst#   _parsed_fields_and_matching_regexes(   t   selft   patternt   fieldst   unused_(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt   __init__6   s    	$c         C` s   |  j  S(   N(   R   (   R   (    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyR   N   s    c         C` s   |  j  S(   N(   R   (   R   (    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt   pattern_partsR   s    c         C` s   |  j  S(   N(   R   (   R   (    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt"   parsed_fields_and_matching_regexesV   s    c         G` s_   g  } xI |  j  D]> } |  j | ƒ s5 | j | ƒ q | j |  j | | ƒ ƒ q Wd j | ƒ S(   up  
    Substitute fields in the string pattern. Return the processed string.
    
    If any substitution function raises an exception, the original string
    pattern is returned.
    
    You may pass additional arguments if `fields` contains functions expecting
    more arguments outside the parsed arguments. These arguments are prepended
    to each function.
    u    (   R   t	   _is_fieldt   appendt   _process_fieldt   join(   R   t   additional_argsR   t   part(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt
   substituteZ   s    c         C` si   |  j  | d d ƒ\ } } } xD | D]< } | d } | d | k oT | d k n r% | d Sq% Wd S(   u   
    If the pattern contains a field at the given character position (starting
    from 0), return the field name, otherwise return `None`.
    R   i   i    i   N(   R   R	   (   t   clsR   t   positionR   t   parsed_fieldst   parsed_fieldt   indices(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt   get_field_at_positionn   s    
$c         C` sÃ   g  } x­ | D]¥ } |  j  | ƒ s2 | j | ƒ q | sG t d ƒ ‚ n  | d g } t | ƒ d k r“ | j g  | d D] } t | ƒ ^ qw ƒ n  | j d j d j | ƒ ƒ ƒ q Wd j | ƒ S(   u  
    Reconstruct a string pattern given the parsed `pattern_parts` returned from
    the `pattern_parts` attribute of a `StringPattern` instance.
    
    Raises:
    
    * `ValueError` - A list as an element of `pattern_parts` representing a
      field is empty.
    uB   lists representing fields must always contain at least one elementi    i   u   [{}]u   , u    (   R   R   t
   ValueErrort   lent   extendt   strt   formatR   (   R   R   t   processed_pattern_partsR   t   field_componentst   arg(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt   reconstruct_pattern}   s    -#c         ` s   t  ‡  f d †  | Dƒ d ƒ S(   u·   
    Given the field `parsed_field_str` and the list of field regular
    expressions, return the first matching field regular expression. Return
    `None` if there is no match.
    c         3` s'   |  ] } t  j | ˆ  ƒ r | Vq d  S(   N(   t   ret   search(   t   .0t   field_regex(   t   parsed_field_str(    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pys	   <genexpr>£   s    N(   t   nextR	   (   R/   t   field_regexes(    (   R/   sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt   get_first_matching_field_regex›   s    c         ` sA  d } d ‰ d ‰  d } g  ‰ g  } i  } d ‡  ‡ ‡ ‡ f d † } xå| t ˆ ƒ k  r,ˆ | d k rP|  j ˆ | d ƒ } | d k rÂ | rÂ | | ƒ ˆ j d ƒ | d ‰  | d 7} qH q| d k rò | rò | | ƒ | ‰ | d 7} q| d k r| d 7} q| d k r-| r-| d 7} qH q| d k r| r| d 7} qnÏˆ | d k r|  j ˆ | d ƒ } | d k r¸| r¸| | ƒ ˆ j d ƒ | d ‰  | d 7} qH n‹ | d k rÛ| rÛ| d 7} qH nh | d k rô| d 8} nO | d k r| r| d 7} qH n- | d k rC| rC| d 8} | d 7} qH n  ˆ ˆ d | !}	 t |  j |	 ƒ ƒ |	 g ˆ d | f g }
 | d k	 r¦|  j |
 d | ƒ } n d } | d k sÙ| d k	 r|  j |
 | | ƒ rˆ j |
 ƒ | j |
 ƒ | | |
 d <n | | d ƒ | d ‰  n  | d 7} qH W| ƒ  ˆ | | f S(   u¢  Parses the given string pattern.
    
    Optionally, only the specified fields will be parsed. `fields` is a
    dictionary containing (field regex, function) pairs.
    
    The following tuple is returned:
    * List of parts forming the pattern. The list contains substrings outside
      fields and parsed fields (the second tuple item).
    * List of parsed fields. Each parsed field contains the following elements:
      field name, list of field arguments, the entire field as a string, tuple
      of (field start position in `pattern`, field end position in `pattern`).
    * List of parsed fields and matching field regexes, if `fields` is not
      `None`.
    i    c         ` sG   t  ˆ  ˆ ƒ } |  d  k	 r2 ˆ j ˆ | |  !ƒ n ˆ j ˆ | ƒ d  S(   N(   t   maxR	   R   (   t	   end_indext   start_index(   t   last_constant_substring_indexR   R   t   start_of_field_index(    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt   _add_pattern_partÅ   s    u   [i   i   u   ]N(   R	   R#   t   _is_field_symbol_escapedR   t   listt   parse_fieldR2   t   _is_field_valid(   R   R   R   t   indext   field_depthR   R   R8   t
   is_escapedR/   R   t   matching_field_regex(    (   R6   R   R   R7   sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyR   §   s€    











-c   
      C` sj  | j  d ƒ } | d k r+ | j ƒ  g  f S| |  j ƒ  } | | d } | d 7} t } d } d } g  } d „  }	 xã | t | ƒ k  rY| | d k rÐ | r¯ | d 7} qw qL| j | | | !ƒ | d } n| | | d k r|  j | | d ƒ r| d 7} qw qLt } n> | | d k rL|  j | | d ƒ rC| d 7} qw qLt } n  | d 7} qw W| |	 | ƒ f S(	   uÖ   Parses the given field as a string.
    
    `field_str` must be specified without `[` and `]` at the beginning and end,
    respectively.
    
    A tuple of (field name, list of field arguments) is returned.
    u   ,iÿÿÿÿi   i    c         S` sŽ   g  } x |  D]y } | j  ƒ  } | s+ q n  | d d k r[ | d d k r[ | d d !} n  | j d d ƒ j d d ƒ } | j | ƒ q W| S(   Ni    u   [iÿÿÿÿu   ]i   u   [[u   ]](   t   stript   replaceR   (   t
   field_argst   processed_field_argst	   field_argt   processed_arg(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt   _process_field_args*  s     u   [i   u   ](   t   findRA   t   FalseR#   R   R9   t   True(
   R   t	   field_strt   field_name_end_indext
   field_namet   field_args_strt   is_in_field_argt   last_field_arg_end_indexR=   RC   RG   (    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyR;     s<    	
	

	
	c         C` sA   | | } t  j | ƒ } | j r= t d j | j ƒ ƒ ‚ n  t S(   NuP   {}: field functions with variable keyword arguments (**kwargs) are not supported(   t   inspectt
   getargspect   keywordsR"   R&   t   __name__RJ   (   R   R   R.   R   t
   field_funct   argspec(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyR<   R  s    
	c         C` s(   | d t  |  ƒ k  o' |  | d | k S(   Ni   (   R#   (   R   R=   t   symbol(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyR9   _  s    c         C` s   t  |  t j ƒ S(   N(   t
   isinstancet   typest   StringTypes(   t   pattern_part(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyR   c  s    c         C` s}   |  j  |  j | d } t | ƒ | d g t | d ƒ } y | | Œ  } Wn t k
 rn d j | d ƒ SXt | ƒ Sd  S(   Ni    i   u   [{}]i   (   R
   R   R:   t	   ExceptionR&   R%   (   R   t   fieldR   RU   t   field_func_argst   return_value(    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyR   g  s    %N(   RT   t
   __module__t   __doc__R	   R   t   propertyR   R   R   R   t   classmethodR!   R*   t   staticmethodR2   R   R;   R<   R9   R   R   (    (    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyR      s    !	j@(   Ra   t
   __future__R    R   R   R   t   future.builtinsR   RQ   R+   RY   t   __all__t   objectR   (    (    (    sN   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/path/pattern.pyt   <module>   s   "
	                                                                                       # -*- coding: utf-8 -*-

"""Functions to modify strings or file paths to make them unique."""

from __future__ import absolute_import, division, print_function, unicode_literals
from future.builtins import *

import os

__all__ = [
  'uniquify_string',
  'uniquify_filepath',
  'uniquify_string_generic',
]


def uniquify_string(str_, existing_strings, position=None, generator=None):
  """
  If string `str_` is in the `existing_strings` list, return a unique string
  by inserting a substring that makes `str_` unique. Otherwise, return original
  `str_`.
  
  Parameters:
  
  * `str_` - String to uniquify.
  
  * `existing_strings` - List of strings to compare against `str_`.
  
  * `position` - See the `position` parameter in `uniquify_string_generic()` for
    more information.
  
  * `generator` - See the `generator` parameter in `uniquify_string_generic()`.
  """
  return uniquify_string_generic(
    str_,
    lambda str_param: str_param not in existing_strings,
    position,
    generator)
  

def uniquify_filepath(filepath, position=None, generator=None):
  """
  If a file at the specified path already exists, return a unique file path.
  
  Parameters:
  
  * `filepath` - File path to uniquify.
  
  * `position` - See the `position` parameter in `uniquify_string_generic()` for
    more information.
  
  * `generator` - See the `generator` parameter in `uniquify_string_generic()`.
  """
  return uniquify_string_generic(
    filepath,
    lambda filepath_param: not os.path.exists(filepath_param),
    position,
    generator)


def uniquify_string_generic(str_, is_unique_func, position=None, generator=None):
  """
  If string `str_` is not unique according to `is_unique_func`, return a unique
  string by inserting a substring that makes `str_` unique. Otherwise, return
  original `str_`.
  
  Parameters:
  
  * `str_` - String to uniquify.
  
  * `is_unique_func` - Function that returns `True` if `str_` is unique, `False`
    otherwise. `is_unique_func` must contain `str_` as its only parameter.
  
  * `position` - Position (index) where the substring is inserted.
    If the position is `None`, insert the substring at the end of `str_` (i.e.
    append it).
  
  * `generator` - A generator object that generates a unique substring in each
    iteration. If `None`, the generator yields default strings - " (1)", " (2)",
    etc.
    
    An example of a custom generator:

      def _generate_unique_copy_string():
        substr = " - copy"
        yield substr
        
        substr = " - another copy"
        yield substr
         
        i = 2
        while True:
          yield "{} {}".format(substr, i)
          i += 1
    
    This generator yields " - copy", " - another copy", " - another copy 2",
    etc.
  """
  
  def _get_uniquified_string(generator):
    return '{}{}{}'.format(
      str_[0:position], next(generator), str_[position:])

  def _generate_unique_number():
    i = 1
    while True:
      yield ' ({})'.format(i)
      i += 1
  
  if is_unique_func(str_):
    return str_
  
  if position is None:
    position = len(str_)
  
  if generator is None:
    generator = _generate_unique_number()
  
  uniq_str = _get_uniquified_string(generator)
  while not is_unique_func(uniq_str):
    uniq_str = _get_uniquified_string(generator)
  
  return uniq_str
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        