
dc           @` s+  d  Z  d d l m Z m Z m 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 Z e j d  Z e j e j  Z e j   Z e j e  e j e  e j e j  d d l m Z m Z e d d d d	 g  Z i d
 d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d  d! 6d" d# 6Z e e e j    e e  @ d k st  d^ d_ d` da db dc dd de df dg dh di dj dk dl dm dn do g Z  dF e! f dG     YZ" dH e! f dI     YZ# e r,e e e j    e e j$  @ d k s,t  n  dJ   Z% dK   Z& dL   Z' dM e! f dN     YZ( dO   Z) dP   Z* dQ   Z+ dR   Z, e- dS  Z. dT   Z/ dU   Z0 e1 e dV  si  e _2 n  dW   Z3 e- dX  Z4 dY   Z5 dZ e! f d[     YZ6 d
 d d d  d d d d d\ d d d d" d g Z7 d]   Z8 d S(p   s  
Python 3 reorganized the standard library (PEP 3108). This module exposes
several standard library modules to Python 2 under their new Python 3
names.

It is designed to be used as follows::

    from future import standard_library
    standard_library.install_aliases()

And then these normal Py3 imports work on both Py3 and Py2::

    import builtins
    import copyreg
    import queue
    import reprlib
    import socketserver
    import winreg    # on Windows only
    import test.support
    import html, html.parser, html.entites
    import http, http.client, http.server
    import http.cookies, http.cookiejar
    import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
    import xmlrpc.client, xmlrpc.server

    import _thread
    import _dummy_thread
    import _markupbase

    from itertools import filterfalse, zip_longest
    from sys import intern
    from collections import UserDict, UserList, UserString
    from collections import OrderedDict, Counter     # even on Py2.6
    from subprocess import getoutput, getstatusoutput
    from subprocess import check_output              # even on Py2.6

(The renamed modules and functions are still available under their old
names on Python 2.)

This is a cleaner alternative to this idiom (see
http://docs.pythonsprints.com/python3_porting/py-porting.html)::

    try:
        import queue
    except ImportError:
        import Queue as queue


Limitations
-----------
We don't currently support these modules, but would like to::

    import dbm
    import dbm.dumb
    import dbm.gnu
    import collections.abc  # on Py33
    import pickle     # should (optionally) bring in cPickle on Python 2

i    (   t   absolute_importt   divisiont   print_functionNt   future_stdlib(   t   PY2t   PY3t   testt   urllibt   picklet   dbmt   builtinst   __builtin__t   copyregt   copy_regt   queuet   Queuet   socketservers   future.moves.socketservert   configparsert   ConfigParsert   reprlibt   reprt   winregt   _winregt   _threadt   threadt   _dummy_threadt   dummy_threadt   xmlrpcs   future.moves.xmlrpct   htmls   future.moves.htmlt   https   future.moves.httpt   _markupbases   future.moves._markupbaset   collectionst   UserListt   UserDictt
   UserStringt	   itertoolst   filterfalset   ifilterfalset   zip_longestt   izip_longestt   syst   internt   ret   ASCIIt   statt   ST_MODEt   base64t   encodebytest   encodestringt   decodebytest   decodestringt
   subprocesst	   getoutputt   commandst   getstatusoutputt   check_outputs   future.backports.misct   matht   ceilt   OrderedDictt   Countert   countt   recursive_reprt	   functoolst
   cmp_to_keyt   RenameImportc           B` s>   e  Z d  Z e Z d   Z d d  Z d   Z d d  Z	 RS(   sX   
    A class for import hooks mapping Py3 module names etc. to the Py2 equivalents.
    c         C` s   | |  _  t | j    t | j    @} t |  d k rg t t | j     t | j    k ss t d   t d   | j   D  |  _ d S(   s   
        Pass in a dictionary-like object mapping from old names to new
        names. E.g. {'ConfigParser': 'configparser', 'cPickle': 'pickle'}
        i    s/   Ambiguity in renaming (handler not implemented)c         s` s!   |  ] \ } } | | f Vq d  S(   N(    (   t   .0t   oldt   new(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pys	   <genexpr>   s    N(	   t
   old_to_newt   sett   keyst   valuest   lent   AssertionErrort   dictt   itemst
   new_to_old(   t   selfRD   t   both(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   __init__   s    	"-	c         C` sC   t  g  |  j D] } | j d  d ^ q  } | | k r? |  Sd  S(   Nt   .i    (   RE   RL   t   splitt   None(   RM   t   fullnamet   patht   st   new_base_names(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   find_module   s    /c         C` sn   d  } | t j k r  t j | S| |  j k rN |  j | } |  j |  } n |  j |  } | t j | <| S(   N(   RR   R(   t   modulesRL   t   _find_and_load_module(   RM   t   nameRT   t   oldnamet   module(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   load_module  s    c         C` s   | j  d  } x t |  d k r | j d  } |  j | |  } y | j } Wq t k
 r t j d j |   | t	 j
 k r t	 j
 | St j d  q Xq W| d } t j | |  } t j | |  S(   sb   
        Finds and loads it. But if there's a . in the name, handles it
        properly.
        RP   i   i    s   Package {0} has no __path__.s   What to do here?(   RQ   RH   t   popRY   t   __path__t   AttributeErrort   flogt   debugt   formatR(   RX   t   impRW   R]   (   RM   RZ   RT   t   bitst   packagenamet   packaget   module_info(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRY     s    
N(
   t   __name__t
   __module__t   __doc__t   Truet   RENAMERRO   RR   RW   R]   RY   (    (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyR@      s   		t   hooksc           B` s    e  Z d  Z d   Z d   Z RS(   s  
    Acts as a context manager. Saves the state of sys.modules and restores it
    after the 'with' block.

    Use like this:

    >>> from future import standard_library
    >>> with standard_library.hooks():
    ...     import http.client
    >>> import requests

    For this to work, http.client will be scrubbed from sys.modules after the
    'with' block. That way the modules imported in the 'with' block will
    continue to be accessible in the current namespace but not from any
    imported modules (like requests).
    c         C` s,   t  j  t j  |  _ t   |  _ t   |  S(   N(   t   copyR(   RX   t   old_sys_modulest   detect_hookst   hooks_were_installedt   install_hooks(   RM   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt	   __enter__?  s    c         G` s   |  j  s t   n  d  S(   N(   Rr   t   remove_hooks(   RM   t   args(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   __exit__G  s    	(   Ri   Rj   Rk   Rt   Rw   (    (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRn   .  s   	c         C` s  t  r
 t Sd t j k r t j t j t j g } g  | D] } t j j	 |  d ^ q8 } t
 t |   d k s t j d |  n  | d t _ n  |  j t j k r t St |  d  r t j j	 |  j  } | d j t j  r d | d k r t Sn  t S(   s   
    Tries to infer whether the module m is from the Python 2 standard library.
    This may not be reliable on all systems.
    t   stdlib_pathi    i   s<   Multiple locations found for the Python standard library: %st   __file__s   site-packages(   R   t   Falset   is_py2_stdlib_modulet   __dict__t
   contextlibRy   t   osRo   RT   RQ   RH   RE   Ra   t   warnRx   Ri   R(   t   builtin_module_namesRl   t   hasattrt
   startswith(   t   mt   stdlib_filest   ft   stdlib_pathst   modpath(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyR{   T  s"    )	c          C` s   t  r
 i  Si  }  x t t t j    @D]h } | t j k rB q' n  t j | } t |  r' t j	 d j
 |   t j | |  | <t j | =q' q' W|  S(   sE  
    Removes any Python 2 standard library modules from ``sys.modules`` that
    would interfere with Py3-style imports using import hooks. Examples are
    modules with the same names (like urllib or email).

    (Note that currently import hooks are disabled for modules like these
    with ambiguous names anyway ...)
    s"   Deleting (Py2) {} from sys.modules(   R   t   REPLACED_MODULESRE   t   RENAMESRF   R(   RX   R{   Ra   Rb   Rc   (   t   scrubbedt
   modulenameR\   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   scrub_py2_sys_modulesr  s    	c           C` s   i  S(   s   
    Deprecated.
    (    (    (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   scrub_future_sys_modules  s    t   suspend_hooksc           B` s    e  Z d  Z d   Z d   Z RS(   s  
    Acts as a context manager. Use like this:

    >>> from future import standard_library
    >>> standard_library.install_hooks()
    >>> import http.client
    >>> # ...
    >>> with standard_library.suspend_hooks():
    >>>     import requests     # incompatible with ``future``'s standard library hooks

    If the hooks were disabled before the context, they are not installed when
    the context is left.
    c         C` s   t    |  _ t   |  S(   N(   Rq   Rr   Ru   (   RM   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRt     s    c         G` s   |  j  r t   n  d  S(   N(   Rr   Rs   (   RM   Rv   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRw     s    	(   Ri   Rj   Rk   Rt   Rw   (    (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyR     s   	c         C` sg   t  t j  t  |   @} t |  d k rS t |  d } t d j |    n  t j j |   d S(   sp   
    Add any previously scrubbed modules back to the sys.modules cache,
    but only if it's safe to do so.
    i    s(   future module {} clashes with Py2 moduleN(   RE   R(   RX   RH   t   listt   ImportErrorRc   t   update(   R   t   clasht   first(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   restore_sys_modules  s    	c          C` sj  t  r
 d Sxg t D]_ \ }  } } } t |   t j |  } t |  t j | } t | |  } t | | |  q Wd d l } d d l m	 } d d l m
 }	 d d l m }
 d d l m } d d l m } | | _	 |	 | _
 |
 | _ | | _ | | _ | t j d <|	 t j d	 <|
 t j d
 <| t j d <| t j d <y d d l } Wn t k
 ran Xy d d l m } Wn t k
 rn X| | _ | t j d <y d d l } Wn t k
 rn Xd d l m } | | _ | t j d <y d d l m } Wn t k
 rn X| | _ | t j d <y d d l m } Wn t k
 rOn X| | _ | t j d <d S(   sm   
    Monkey-patches the standard library in Py2.6/7 to provide
    aliases for better Py3 compatibility.
    Ni    (   t   request(   t   response(   t   parse(   t   error(   t   robotparsers   urllib.requests   urllib.responses   urllib.parses   urllib.errors   urllib.robotparser(   t   supports   test.support(   t   dumbs   dbm.dumb(   t   gnus   dbm.gnu(   t   ndbms   dbm.ndbm(   R   t   MOVESt
   __import__R(   RX   t   getattrt   setattrR   t   future.backports.urllibR   R   R   R   R   R   R   t   future.moves.testR   R	   t   future.moves.dbmR   R   R   (   t
   newmodnamet
   newobjnamet
   oldmodnamet
   oldobjnamet   newmodt   oldmodt   objR   R   R   R   R   R   R   R   R	   R   R   R   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   install_aliases  sl    

									c          C` s|   t  r
 d St   t j d j t j   t j d  t t  }  t	   s_ t j j
 |   n  t j d j t j   d S(   s`   
    This function installs the future.standard_library import hook into
    sys.meta_path.
    Ns   sys.meta_path was: {0}s   Installing hooks ...s   sys.meta_path is now: {0}(   R   R   Ra   Rb   Rc   R(   t	   meta_pathR@   R   Rq   t   append(   t   newhook(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRs   	  s    	c           C` s   t    d S(   s_   
    Deprecated. Use install_hooks() instead. This will be removed by
    ``future`` v1.0.
    N(   Rs   (    (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   enable_hooks  s    c         C` sz   t  r
 d St j d  xL t t t j   d d d  D]( \ } } t | d  r: t j | =q: q: W|  rv t   n  d S(   sC   
    This function removes the import hook from sys.meta_path.
    Ns   Uninstalling hooks ...iRm   (	   R   Ra   Rb   R   t	   enumerateR(   R   R   R   (   t   scrub_sys_modulest   it   hook(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRu   %  s    /c           C` s   t    d S(   s^   
    Deprecated. Use remove_hooks() instead. This will be removed by
    ``future`` v1.0.
    N(   Ru   (    (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   disable_hooks9  s    c          C` s_   t  j d  t g  t j D] }  t |  d  ^ q  } | rN t  j d  n t  j d  | S(   sG   
    Returns True if the import hooks are installed, False if not.
    s   Detecting hooks ...Rm   s	   Detected.s   Not detected.(   Ra   Rb   t   anyR(   R   R   (   R   t   present(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRq   A  s    +t   py2_modulesc          C` sx   t  t j  d k r d St   s) t  d d l }  |  t j d <d d l } | t j d <d d l } | t j d <d S(   s   
    Currently this function is unneeded, as we are not attempting to provide import hooks
    for modules with ambiguous names: email, urllib, pickle.
    i    NR   t   emailR   (   RH   R(   R   Rq   RI   R   R   R   (   R   R   R   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   cache_py2_modulesV  s    c   	      C` s   d d l  } t r t |   S| r+ d } n d } | j d  |  j d  } g  } xG t |  D]9 \ } } d j | | d   } | j | j |   q` WxR t t	 t |    D]8 \ } } | d k r Pn  t
 | | d | | |  q W| d Sd S(   s  
    Pass a (potentially dotted) module name of a Python 3 standard library
    module. This function imports the module compatibly on Py2 and Py3 and
    returns the top-level module.

    Example use:
        >>> http = import_('http.client')
        >>> http = import_('http.server')
        >>> urllib = import_('urllib.request')

    Then:
        >>> conn = http.client.HTTPConnection(...)
        >>> response = urllib.request.urlopen('http://mywebsite.com')
        >>> # etc.

    Use as follows:
        >>> package_name = import_(module_name)

    On Py3, equivalent to this:

        >>> import module_name

    On Py2, equivalent to this if backport=False:

        >>> from future.moves import module_name

    or to this if backport=True:

        >>> from future.backports import module_name

    except that it also handles dotted module names such as ``http.client``
    The effect then is like this:

        >>> from future.backports import module
        >>> from future.backports.module import submodule
        >>> module.submodule = submodule

    Note that this would be a SyntaxError in Python:

        >>> from future.backports import http.client

    i    Ns   future.backportss   future.movesRP   i   i   (   t	   importlibR   R   RQ   R   t   joinR   t   import_modulet   reversedR   R   (	   t   module_namet   backportR   t   prefixt   partsRX   R   t   partt   sofar(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   import_r  s     .
	% c         O` s   t  r t |   Sd | k r5 t | d  r5 d } n d } | j d  |  j d  } t j | d |   } g  | D] } t | |  ^ qu } t |  d k r | d S| Sd S(   sa  
    Example use:
        >>> HTTPConnection = from_import('http.client', 'HTTPConnection')
        >>> HTTPServer = from_import('http.server', 'HTTPServer')
        >>> urlopen, urlparse = from_import('urllib.request', 'urlopen', 'urlparse')

    Equivalent to this on Py3:

        >>> from module_name import symbol_names[0], symbol_names[1], ...

    and this on Py2:

        >>> from future.moves.module_name import symbol_names[0], ...

    or:

        >>> from future.backports.module_name import symbol_names[0], ...

    except that it also handles dotted module names such as ``http.client``.
    R   s   future.backportss   future.movesRP   i   i    N(   R   R   t   boolRQ   R   R   R   RH   (   R   t   symbol_namest   kwargsR   R   R\   RZ   t   output(    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   from_import  s    
	"t   exclude_local_folder_importsc           B` s)   e  Z d  Z d   Z d   Z d   Z RS(   sZ  
    A context-manager that prevents standard library modules like configparser
    from being imported from the local python-future source folder on Py3.

    (This was need prior to v0.16.0 because the presence of a configparser
    folder would otherwise have prevented setuptools from running on Py3. Maybe
    it's not needed any more?)
    c         G` s\   t  |  d k s t  | |  _ t g  |  j D] } d | k ^ q.  rX t d   n  d  S(   Ni    RP   s%   Dotted module names are not supported(   RH   RI   t   module_namesR   t   NotImplementedError(   RM   Rv   R   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRO     s    	(c         C` s   t  j  t j  |  _ t  j  t j  |  _ t j d d k  rA d  Sd d d d d g } x^ |  j D]S } t g  | D]' } t j j	 t j j
 | |   ^ qp  r` t j j |  q` q` Wx; |  j D]0 } y t | d d } Wq t k
 r q Xq Wd  S(	   Ni    i   t   futuret   pastt   libfuturizet   libpasteurizeR
   t   level(   Ro   R(   RT   t   old_sys_pathRX   Rp   t   version_infot   allR~   t   existsR   t   removeR   R   R   (   RM   t   FUTURE_SOURCE_SUBFOLDERSt   foldert	   subfolderR   R\   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRt     s    4c         G` sW   |  j  t _ xD t |  j j    t t j j    D] } |  j | t j | <q5 Wd  S(   N(   R   R(   RT   RE   Rp   RF   RX   (   RM   Rv   R   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyRw     s    /(   Ri   Rj   Rk   RO   Rt   Rw   (    (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyR     s   		 t   tkinterc       
   C` sJ   t  t   8 x0 t D]( }  y t |   Wq t k
 r; q Xq WWd  QXd  S(   N(   R   t   TOP_LEVEL_MODULESR   R   (   R   (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   import_top_level_modules'  s    (   R   R    R    R    (   R   R!   R!   R!   (   R   R"   R"   R"   (   R#   R$   R#   R%   (   R#   R&   R#   R'   (   R(   R)   R   R)   (   R*   R+   R,   R-   (   R.   R/   R.   R0   (   R.   R1   R.   R2   (   R3   R4   R5   R4   (   R3   R6   R5   R6   (   R3   R7   s   future.backports.miscR7   (   R8   R9   s   future.backports.miscR9   (   R   R:   s   future.backports.miscR:   (   R   R;   s   future.backports.miscR;   (   R#   R<   s   future.backports.miscR<   (   R   R=   s   future.backports.miscR=   (   R>   R?   s   future.backports.miscR?   (9   Rk   t
   __future__R    R   R   R(   t   loggingRd   R}   t   typesRo   R~   t	   getLoggerRa   t	   Formattert   BASIC_FORMATt
   _formattert   StreamHandlert   _handlert   setFormattert
   addHandlert   setLevelt   WARNt   future.utilsR   R   RE   R   R   RH   RG   RI   R   t   objectR@   Rn   R   R{   R   R   R   R   R   Rs   R   Rz   Ru   R   Rq   R   R   R   R   R   R   R   R   (    (    (    sn   /home/josie/.config/GIMP/2.10/plug-ins/export_layers/pygimplib/_lib/future/future/standard_library/__init__.pyt   <module>;   s   


.	 F"4					P					I	&6	                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  from __future__ import print_function, absolute_import
import os
import tempfile
import unittest
import sys
import re
import warnings
import io
from textwrap import dedent

from future.utils import bind_method, PY26, PY3, PY2, PY27
from future.moves.subprocess import check_output, STDOUT, CalledProcessError

if PY26:
    import unittest2 as unittest


def reformat_code(code):
    """
    Removes any leading \n and dedents.
    """
    if code.startswith('\n'):
        code = code[1:]
    return dedent(code)


def order_future_lines(code):
    """
    Returns the code block with any ``__future__`` import lines sorted, and
    then any ``future`` import lines sorted, then any ``builtins`` import lines
    sorted.

    This only sorts the lines within the expected blocks.

    See test_order_future_lines() for an example.
    """

    # We need .splitlines(keepends=True), which doesn't exist on Py2,
    # so we use this instead:
    lines = code.split('\n')

    uufuture_line_numbers = [i for i, line in enumerate(lines)
                               if line.startswith('from __future__ import ')]

    future_line_numbers = [i for i, line in enumerate(lines)
                             if line.startswith('from future')
                             or line.startswith('from past')]

    builtins_line_numbers = [i for i, line in enumerate(lines)
                             if line.startswith('from builtins')]

    assert code.lstrip() == code, ('internal usage error: '
            'dedent the code before calling order_future_lines()')

    def mymax(numbers):
        return max(numbers) if len(numbers) > 0 else 0

    def mymin(numbers):
        return min(numbers) if len(numbers) > 0 else float('inf')

    assert mymax(uufuture_line_numbers) <= mymin(future_line_numbers), \
            'the __future__ and future imports are out of order'

    # assert mymax(future_line_numbers) <= mymin(builtins_line_numbers), \
    #         'the future and builtins imports are out of order'

    uul = sorted([lines[i] for i in uufuture_line_numbers])
    sorted_uufuture_lines = dict(zip(uufuture_line_numbers, uul))

    fl = sorted([lines[i] for i in future_line_numbers])
    sorted_future_lines = dict(zip(future_line_numbers, fl))

    bl = sorted([lines[i] for i in builtins_line_numbers])
    sorted_builtins_lines = dict(zip(builtins_line_numbers, bl))

    # Replace the old unsorted "from __future__ import ..." lines with the
    # new sorted ones:
    new_lines = []
    for i in range(len(lines)):
        if i in uufuture_line_numbers:
            new_lines.append(sorted_uufuture_lines[i])
        elif i in future_line_numbers:
            new_lines.append(sorted_future_lines[i])
        elif i in builtins_line_numbers:
            new_lines.append(sorted_builtins_lines[i])
        else:
            new_lines.append(lines[i])
    return '\n'.join(new_lines)


class VerboseCalledProcessError(CalledProcessError):
    """
    Like CalledProcessError, but it displays more information (message and
    script output) for diagnosing test failures etc.
    """
    def __init__(self, msg, returncode, cmd, output=None):
        self.msg = msg
        self.returncode = returncode
        self.cmd = cmd
        self.output = output

    def __str__(self):
        return ("Command '%s' failed with exit status %d\nMessage: %s\nOutput: %s"
                % (self.cmd, self.returncode, self.msg, self.output))

class FuturizeError(VerboseCalledProcessError):
    pass

class PasteurizeError(VerboseCalledProcessError):
    pass


class CodeHandler(unittest.TestCase):
    """
    Handy mixin for test classes for writing / reading / futurizing /
    running .py files in the test suite.
    """
    def setUp(self):
        """
        The outputs from the various futurize stages should have the
        following headers:
        """
        # After stage1:
        # TODO: use this form after implementing a fixer to consolidate
        #       __future__ imports into a single line:
        # self.headers1 = """
        # from __future__ import absolute_import, division, print_function
        # """
        self.headers1 = reformat_code("""
        from __future__ import absolute_import
        from __future__ import division
        from __future__ import print_function
        """)

        # After stage2 --all-imports:
        # TODO: use this form after implementing a fixer to consolidate
        #       __future__ imports into a single line:
        # self.headers2 = """
        # from __future__ import (absolute_import, division,
        #                         print_function, unicode_literals)
        # from future import standard_library
        # from future.builtins import *
        # """
        self.headers2 = reformat_code("""
        from __future__ import absolute_import
        from __future__ import division
        from __future__ import print_function
        from __future__ import unicode_literals
        from future import standard_library
        standard_library.install_aliases()
        from builtins import *
        """)
        self.interpreters = [sys.executable]
        self.tempdir = tempfile.mkdtemp() + os.path.sep
        pypath = os.getenv('PYTHONPATH')
        if pypath:
            self.env = {'PYTHONPATH': os.getcwd() + os.pathsep + pypath}
        else:
            self.env = {'PYTHONPATH': os.getcwd()}

    def convert(self, code, stages=(1, 2), all_imports=False, from3=False,
                reformat=True, run=True, conservative=False):
        """
        Converts the code block using ``futurize`` and returns the
        resulting code.
        
        Passing stages=[1] or stages=[2] passes the flag ``--stage1`` or
        ``stage2`` to ``futurize``. Passing both stages runs ``futurize``
        with both stages by default.

        If from3 is False, runs ``futurize``, converting from Python 2 to
        both 2 and 3. If from3 is True, runs ``pasteurize`` to convert
        from Python 3 to both 2 and 3.

        Optionally reformats the code block first using the reformat() function.

        If run is True, runs the resulting code under all Python
        interpreters in self.interpreters.
        """
        if reformat:
            code = reformat_code(code)
        self._write_test_script(code)
        self._futurize_test_script(stages=stages, all_imports=all_imports,
                                   from3=from3, conservative=conservative)
        output = self._read_test_script()
        if run:
            for interpreter in self.interpreters:
                _ = self._run_test_script(interpreter=interpreter)
        return output

    def compare(self, output, expected, ignore_imports=True):
        """
        Compares whether the code blocks are equal. If not, raises an
        exception so the test fails. Ignores any trailing whitespace like
        blank lines.

        If ignore_imports is True, passes the code blocks into the
        strip_future_imports method.

        If one code block is a unicode string and the other a
        byte-string, it assumes the byte-string is encoded as utf-8.
        """
        if ignore_imports:
            output = self.strip_future_imports(output)
            expected = self.strip_future_imports(expected)
        if isinstance(output, bytes) and not isinstance(expected, bytes):
            output = output.decode('utf-8')
        if isinstance(expected, bytes) and not isinstance(output, bytes):
            expected = expected.decode('utf-8')
        self.assertEqual(order_future_lines(output.rstrip()),
                         expected.rstrip())

    def strip_future_imports(self, code):
        """
        Strips any of these import lines:

            from __future__ import <anything>
            from future <anything>
            from future.<anything>
            from builtins <anything>

        or any line containing:
            install_hooks()
        or:
            install_aliases()

        Limitation: doesn't handle imports split across multiple lines like
        this:

            from __future__ import (absolute_import, division, print_function,
                                    unicode_literals)
        """
        output = []
        # We need .splitlines(keepends=True), which doesn't exist on Py2,
        # so we use this instead:
        for line in code.split('\n'):
            if not (line.startswith('from __future__ import ')
                    or line.startswith('from future ')
                    or line.startswith('from builtins ')
                    or 'install_hooks()' in line
                    or 'install_aliases()' in line
                    # but don't match "from future_builtins" :)
                    or line.startswith('from future.')):
                output.append(line)
        return '\n'.join(output)

    def convert_check(self, before, expected, stages=(1, 2), all_imports=False,
                      ignore_imports=True, from3=False, run=True,
                      conservative=False):
        """
        Convenience method that calls convert() and compare().

        Reformats the code blocks automatically using the reformat_code()
        function.

        If all_imports is passed, we add the appropriate import headers
        for the stage(s) selected to the ``expected`` code-block, so they
        needn't appear repeatedly in the test code.

        If ignore_imports is True, ignores the presence of any lines
        beginning:
        
            from __future__ import ...
            from future import ...
            
        for the purpose of the comparison.
        """
        output = self.convert(before, stages=stages, all_imports=all_imports,
                              from3=from3, run=run, conservative=conservative)
        if all_imports:
            headers = self.headers2 if 2 in stages else self.headers1
        else:
            headers = ''

        self.compare(output, headers + reformat_code(expected),
                     ignore_imports=ignore_imports)

    def unchanged(self, code, **kwargs):
        """
        Convenience method to ensure the code is unchanged by the
        futurize process.
        """
        self.convert_check(code, code, **kwargs)

    def _write_test_script(self, code, filename='mytestscript.py'):
        """
        Dedents the given code (a multiline string) and writes it out to
        a file in a temporary folder like /tmp/tmpUDCn7x/mytestscript.py.
        """
        if isinstance(code, bytes):
            code = code.decode('utf-8')
        # Be explicit about encoding the temp file as UTF-8 (issue #63):
        with io.open(self.tempdir + filename, 'wt', encoding='utf-8') as f:
            f.write(dedent(code))

    def _read_test_script(self, filename='mytestscript.py'):
        with io.open(self.tempdir + filename, 'rt', encoding='utf-8') as f:
            newsource = f.read()
        return newsource

    def _futurize_test_script(self, filename='mytestscript.py', stages=(1, 2),
                              all_imports=False, from3=False,
                              conservative=False):
        params = []
        stages = list(stages)
        if all_imports:
            params.append('--all-imports')
        if from3:
            script = 'pasteurize.py'
        else:
            script = 'futurize.py'
            if stages == [1]:
                params.append('--stage1')
            elif stages == [2]:
                params.append('--stage2')
            else:
                assert stages == [1, 2]
            if conservative:
                params.append('--conservative')
            # No extra params needed

        # Absolute file path:
        fn = self.tempdir + filename
        call_args = [sys.executable, script] + params + ['-w', fn]
        try:
            output = check_output(call_args, stderr=STDOUT, env=self.env)
        except CalledProcessError as e:
            with open(fn) as f:
                msg = (
                    'Error running the command %s\n'
                    '%s\n'
                    'Contents of file %s:\n'
                    '\n'
                    '%s') % (
                        ' '.join(call_args),
                        'env=%s' % self.env,
                        fn,
                        '----\n%s\n----' % f.read(),
                    )
            ErrorClass = (FuturizeError if 'futurize' in script else PasteurizeError)
            raise ErrorClass(msg, e.returncode, e.cmd, output=e.output)
        return output

    def _run_test_script(self, filename='mytestscript.py',
                         interpreter=sys.executable):
        # Absolute file path:
        fn = self.tempdir + filename
        try:
            output = check_output([interpreter, fn],
                                  env=self.env, stderr=STDOUT)
        except CalledProcessError as e:
            with open(fn) as f:
                msg = (
                    'Error running the command %s\n'
                    '%s\n'
                    'Contents of file %s:\n'
                    '\n'
                    '%s') % (
                        ' '.join([interpreter, fn]),
                        'env=%s' % self.env,
                        fn,
                        '----\n%s\n----' % f.read(),
                    )
            if not hasattr(e, 'output'):
                # The attribute CalledProcessError.output doesn't exist on Py2.6
                e.output = None
            raise VerboseCalledProcessError(msg, e.returncode, e.cmd, output=e.output)
        return output


# Decorator to skip some tests on Python 2.6 ...
skip26 = unittest.skipIf(PY26, "this test is known to fail on Py2.6")


def expectedFailurePY3(func):
    if not PY3:
        return func
    return unittest.expectedFailure(func)

def expectedFailurePY26(func):
    if not PY26:
        return func
    return unittest.expectedFailure(func)


def expectedFailurePY27(func):
    if not PY27:
        return func
    return unittest.expectedFailure(func)


def expectedFailurePY2(func):
    if not PY2:
        return func
    return unittest.expectedFailure(func)


# Renamed in Py3.3:
if not hasattr(unittest.TestCase, 'assertRaisesRegex'):
    unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp

# From Py3.3:
def assertRegex(self, text, expected_regex, msg=None):
    """Fail the test unless the text matches the regular expression."""
    if isinstance(expected_regex, (str, unicode)):
        assert expected_regex, "expected_regex must not be empty."
        expected_regex = re.compile(expected_regex)
    if not expected_regex.search(text):
        msg = msg or "Regex didn't match"
        msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
        raise self.failureException(msg)

if not hasattr(unittest.TestCase, 'assertRegex'):
    bind_method(unittest.TestCase, 'assertRegex', assertRegex)

class _AssertRaisesBaseContext(object):

    def __init__(self, expected, test_case, callable_obj=None,
                 expected_regex=None):
        self.expected = expected
        self.test_case = test_case
        if callable_obj is not None:
            try:
                self.obj_name = callable_obj.__name__
            except AttributeError:
                self.obj_name = str(callable_obj)
        else:
            self.obj_name = None
        if isinstance(expected_regex, (bytes, str)):
            expected_regex = re.compile(expected_regex)
        self.expected_regex = expected_regex
        self.msg = None

    def _raiseFailure(self, standardMsg):
        msg = self.test_case._formatMessage(self.msg, standardMsg)
        raise self.test_case.failureException(msg)

    def handle(self, name, callable_obj, args, kwargs):
        """
        If callable_obj is None, assertRaises/Warns is being used as a
        context manager, so check for a 'msg' kwarg and return self.
        If callable_obj is not None, call it passing args and kwargs.
        """
        if callable_obj is None:
            self.msg = kwargs.pop('msg', None)
            return self
        with self:
            callable_obj(*args, **kwargs)

class _AssertWarnsContext(_AssertRaisesBaseContext):
    """A context manager used to implement TestCase.assertWarns* methods."""

    def __enter__(self):
        # The __warningregistry__'s need to be in a pristine state for tests
        # to work properly.
        for v in sys.modules.values():
            if getattr(v, '__warningregistry__', None):
                v.__warningregistry__ = {}
        self.warnings_manager = warnings.catch_warnings(record=True)
        self.warnings = self.warnings_manager.__enter__()
        warnings.simplefilter("always", self.expected)
        return self

    def __exit__(self, exc_type, exc_value, tb):
        self.warnings_manager.__exit__(exc_type, exc_value, tb)
        if exc_type is not None:
            # let unexpected exceptions pass through
            return
        try:
            exc_name = self.expected.__name__
        except AttributeError:
            exc_name = str(self.expected)
        first_matching = None
        for m in self.warnings:
            w = m.message
            if not isinstance(w, self.expected):
                continue
            if first_matching is None:
                first_matching = w
            if (self.expected_regex is not None and
                not self.expected_regex.search(str(w))):
                continue
            # store warning for later retrieval
            self.warning = w
            self.filename = m.filename
            self.lineno = m.lineno
            return
        # Now we simply try to choose a helpful failure message
        if first_matching is not None:
            self._raiseFailure('"{}" does not match "{}"'.format(
                     self.expected_regex.pattern, str(first_matching)))
        if self.obj_name:
            self._raiseFailure("{} not triggered by {}".format(exc_name,
                                                               self.obj_name))
        else:
            self._raiseFailure("{} not triggered".format(exc_name))


def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs):
    """Fail unless a warning of class warnClass is triggered
       by callable_obj when invoked with arguments args and keyword
       arguments kwargs.  If a different type of warning is
       triggered, it will not be handled: depending on the other
       warning filtering rules in effect, it might be silenced, printed
       out, or raised as an exception.

       If called with callable_obj omitted or None, will return a
       context object used like this::

            with self.assertWarns(SomeWarning):
                do_something()

       An optional keyword argument 'msg' can be provided when assertWarns
       is used as a context object.

       The context manager keeps a reference to the first matching
       warning as the 'warning' attribute; similarly, the 'filename'
       and 'lineno' attributes give you information about the line
       of Python code from which the warning was triggered.
       This allows you to inspect the warning after the assertion::

           with self.assertWarns(SomeWarning) as cm:
               do_something()
           the_warning = cm.warning
           self.assertEqual(the_warning.some_attribute, 147)
    """
    context = _AssertWarnsContext(expected_warning, self, callable_obj)
    return context.handle('assertWarns', callable_obj, args, kwargs)

if not hasattr(unittest.TestCase, 'assertWarns'):
    bind_method(unittest.TestCase, 'assertWarns', assertWarns)
                                                                                                                                                                                                                       """
This module contains backports the data types that were significantly changed
in the transition from Python 2 to Python 3.

- an implementation of Python 3's bytes object (pure Python subclass of
  Python 2's builtin 8-bit str type)
- an implementation of Python 3's str object (pure Python subclass of
  Python 2's builtin unicode type)
- a backport of the range iterator from Py3 with slicing support

It is used as follows::

    from __future__ import division, absolute_import, print_function
    from builtins import bytes, dict, int, range, str

to bring in the new semantics for these functions from Python 3. And
then, for example::
    
    b = bytes(b'ABCD')
    assert list(b) == [65, 66, 67, 68]
    assert repr(b) == "b'ABCD'"
    assert [65, 66] in b

    # These raise TypeErrors:
    # b + u'EFGH'
    # b.split(u'B')
    # bytes(b',').join([u'Fred', u'Bill'])


    s = str(u'ABCD')

    # These raise TypeErrors:
    # s.join([b'Fred', b'Bill'])
    # s.startswith(b'A')
    # b'B' in s
    # s.find(b'A')
    # s.replace(u'A', b'a')

    # This raises an AttributeError:
    # s.decode('utf-8')

    assert repr(s) == 'ABCD'      # consistent repr with Py3 (no u prefix)


    for i in range(10**11)[:10]:
        pass

and::
    
    class VerboseList(list):
        def append(self, item):
            print('Adding an item')
            super().append(item)        # new simpler super() function

For more information:
---------------------

- future.types.newbytes
- future.types.newdict
- future.types.newint
- future.types.newobject
- future.types.newrange
- future.types.newstr


Notes
=====

range()
-------
``range`` is a custom class that backports the slicing behaviour from
Python 3 (based on the ``xrange`` module by Dan Crosta). See the
``newrange`` module docstring for more details.


super()
-------
``super()`` is based on Ryan Kelly's ``magicsuper`` module. See the
``newsuper`` module docstring for more details.


round()
-------
Python 3 modifies the behaviour of ``round()`` to use "Banker's Rounding".
See http://stackoverflow.com/a/10825998. See the ``newround`` module
docstring for more details.

"""

from __future__ import absolute_import, division, print_function

import functools
from numbers import Integral

from future import utils


# Some utility functions to enforce strict type-separation of unicode str and
# bytes:
def disallow_types(argnums, disallowed_types):
    """
    A decorator that raises a TypeError if any of the given numbered
    arguments is of the corresponding given type (e.g. bytes or unicode
    string).

    For example:

        @disallow_types([0, 1], [unicode, bytes])
        def f(a, b):
            pass

    raises a TypeError when f is called if a unicode object is passed as
    `a` or a bytes object is passed as `b`.

    This also skips over keyword arguments, so 

        @disallow_types([0, 1], [unicode, bytes])
        def g(a, b=None):
            pass

    doesn't raise an exception if g is called with only one argument a,
    e.g.:

        g(b'Byte string')

    Example use:

    >>> class newbytes(object):
    ...     @disallow_types([1], [unicode])
    ...     def __add__(self, other):
    ...          pass

    >>> newbytes('1234') + u'1234'      #doctest: +IGNORE_EXCEPTION_DETAIL 
    Traceback (most recent call last):
      ...
    TypeError: can't concat 'bytes' to (unicode) str
    """

    def decorator(function):

        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            # These imports are just for this decorator, and are defined here
            # to prevent circular imports:
            from .newbytes import newbytes
            from .newint import newint
            from .newstr import newstr

            errmsg = "argument can't be {0}"
            for (argnum, mytype) in zip(argnums, disallowed_types):
                # Handle the case where the type is passed as a string like 'newbytes'.
                if isinstance(mytype, str) or isinstance(mytype, bytes):
                    mytype = locals()[mytype]

                # Only restrict kw args only if they are passed:
                if len(args) <= argnum:
                    break

                # Here we use type() rather than isinstance() because
                # __instancecheck__ is being overridden. E.g.
                # isinstance(b'abc', newbytes) is True on Py2.
                if type(args[argnum]) == mytype:
                    raise TypeError(errmsg.format(mytype))

            return function(*args, **kwargs)
        return wrapper
    return decorator


def no(mytype, argnums=(1,)):
    """
    A shortcut for the disallow_types decorator that disallows only one type
    (in any position in argnums).

    Example use:

    >>> class newstr(object):
    ...     @no('bytes')
    ...     def __add__(self, other):
    ...          pass

    >>> newstr(u'1234') + b'1234'     #doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    TypeError: argument can't be bytes

    The object can also be passed directly, but passing the string helps
    to prevent circular import problems.
    """
    if isinstance(argnums, Integral):
        argnums = (argnums,)
    disallowed_types = [mytype] * len(argnums)
    return disallow_types(argnums, disallowed_types)


def issubset(list1, list2):
    """
    Examples:

    >>> issubset([], [65, 66, 67])
    True
    >>> issubset([65], [65, 66, 67])
    True
    >>> issubset([65, 66], [65, 66, 67])
    True
    >>> issubset([65, 67], [65, 66, 67])
    False
    """
    n = len(list1)
    for startpos in range(len(list2) - n + 1):
        if list2[startpos:startpos+n] == list1:
            return True
    return False


if utils.PY3:
    import builtins
    bytes = builtins.bytes
    dict = builtins.dict
    int = builtins.int
    list = builtins.list
    object = builtins.object
    range = builtins.range
    str = builtins.str

    # The identity mapping
    newtypes = {bytes: bytes,
                dict: dict,
                int: int,
                list: list,
                object: object,
                range: range,
                str: str}

    __all__ = ['newtypes']

else:

    from .newbytes import newbytes
    from .newdict import newdict
    from .newint import newint
    from .newlist import newlist
    from .newrange import newrange
    from .newobject import newobject
    from .newstr import newstr

    newtypes = {bytes: newbytes,
                dict: newdict,
                int: newint,
                long: newint,
                list: newlist,
                object: newobject,
                range: newrange,
                str: newbytes,
                unicode: newstr}

    __all__ = ['newbytes', 'newdict', 'newint', 'newlist', 'newrange', 'newstr', 'newtypes']

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    