Commits

lowks  committed e82e6c6

Making a few changes to enhpath_test.py to make it pep8 compliant

  • Participants
  • Parent commits 8d25480

Comments (0)

Files changed (1)

File rex/path/enhpath.py

 URL coming soon.
 
 Derived from Jason Orendorff's path.py 2.0.4 (JOP) available at
-http://www.jorendorff.com/articles/python/path.  
+http://www.jorendorff.com/articles/python/path.
 
 Whereas JOP maintains strict API compatibility with its parent functions,
 enhpath ("enhanced path") stresses convenience and conciseness in the caller's
   path()             Same as path('')
   path.cwd()         Same as path(os.getcwd())
                        (JOP: path.getcwd() is static method)
-  path.popdir(N=1)   Pop Nth previous directory off path.pushed_dirs, chdir to 
+  path.popdir(N=1)   Pop Nth previous directory off path.pushed_dirs, chdir to
                        it, and log a debug message.  IndexError if we fall off
                        the end of the list.  See .chdir().  (JOP: no equiv.)
   path.tempfile(suffix='', prefix=tempfile.template, dir=None, text=False)
                      Create a temporary directory using tempfile.mkdtemp and
                        return its path.  The directory will not be
                        automatically deleted.  (JOP: no equivalent.)
-  path.tempfileobject(mode='w+b', bufsize=-1, suffix='', 
+  path.tempfileobject(mode='w+b', bufsize=-1, suffix='',
       prefix=tempfile.template, dir=None)
                      Return a file object pointing to an anonymous temporary
                        file.  The file will automatically be destroyed when the
                  path('/home/joe').realpath() => path('/mnt/data/home/joe')
                  if /home is a symlink to /mnt/data/home.
   .expand()    Call expanduser, expandvars and normpath.  This is commonly
-                 everything you need to clean up a filename from a 
+                 everything you need to clean up a filename from a
                  configuration file.
   .expanduser() Convert ~user to the user's home directory.
                  path('~joe/Mail').expanduser() => path('/home/joe/Mail')
                  no relative path (e.g., they reside on different drives on
                  Windows), same as dest.abspath().  Dest may be a path or a
                  string.
-  .relpathfrom(ancestor)  Chop off the front part of self that matches 
-                 ancestor.  
+  .relpathfrom(ancestor)  Chop off the front part of self that matches
+                 ancestor.
                  path('/home/joe/Mail').relpathfrom('/home/joe')  =>
                  path('Mail')
                  ValueError if self does not start with ancestor.
                   and --odir options.)  (JOP: no equivalent method.)
 
 Listing directories:
-  Common arguments:  
+  Common arguments:
                 pattern, a glob pattern like "*.py".  Limits the result to
                   matching filenames.
                 symlinks, False to exclude symbolic links from result.
-                  Useful if you want to treat them separately.  (JOB: no 
+                  Useful if you want to treat them separately.  (JOB: no
                   equivalent argument.)
 
-  .listdir(pattern=None, symlinks=True, names_only=False)  
+  .listdir(pattern=None, symlinks=True, names_only=False)
                 List directory.
                   path('/').listdir() => [path('/bin'), path('/boot'), ...]
                   path('/').listdir(names_only=True) => ['bin', 'boot', ...]
                   (JOP: No names_only argument.)
   .dirs(pattern=None, symlinks=True)
                 List only the subdirectories in directory.  Not recursive.
-                  path('/usr/lib/python2.3').dirs() => 
+                  path('/usr/lib/python2.3').dirs() =>
                     [path('/usr/lib/python2.3/site-packages'), ...]
   .files(pattern=None, symlinks=True)
                 List only the regular files in directory.  Not recursive.
                   Does not list special files (anything for which
                   os.path.isfile() returns false).
-                  path('/usr/lib/python2.3').dirs() => 
+                  path('/usr/lib/python2.3').dirs() =>
                     [path('/usr/lib/python2.3/BaseHTTPServer.py'), ...]
   .symlinks(pattern=None)
                 List only the symbolic links in directory.  Not recursive.
   .walksymlinks(pattern=None)
                 Same as .walk() but yield only symbolic links.
                   (JOP: no equivalent method.)
-  .findpaths(args=None, ls=False, **kw) 
+  .findpaths(args=None, ls=False, **kw)
                 Run the Unix 'find' command and return an iteration of paths.
                   The argument signature matches find's most popular arguments.
-                  Due to Python's handling of keyword arguments, there are 
+                  Due to Python's handling of keyword arguments, there are
                   some limitations:
                     - You can't specify the same argument multiple times.
                     - The argument order may be rearranged.
                     - mtime=(N, N)
                       Converted to two -mtime options, used to specify a range.
                       Normally the first arg is negative and the second
-                      positive.  Same for atime, ctime, mmin, amin, cmin.  
+                      positive.  Same for atime, ctime, mmin, amin, cmin.
                     - name=[pattern1, pattern2, ...]
                       Converted to '-lbrace -name pattern1 -o ... -rbrace'.
                       Value may be list or tuple.
                   call .normpath() because of its fragility with symbolic
                   links.  On other platforms we don't clean up the paths
                   because we don't know how.
-                  
-  .findpaths_pretend(args=None, ls=False, **kw) 
+
+  .findpaths_pretend(args=None, ls=False, **kw)
                 Same as .find(...) above but don't actually do the find;
                   instead, return the external command line as a list of
                   strings.  Useful for debugging.
   .fnmatch(pattern)  Return True if self.name matches the pattern.
   .glob(pattern)  Return a list of paths that match the pattern.
                   path('a').glob('*.py') => Same as path('a').listdir('*.py')
-                  path('a').glob('*/bin/*') => List of files all users have 
+                  path('a').glob('*/bin/*') => List of files all users have
                                                in their bin directories.
 
-# Reading/writing files                
+# Reading/writing files
   .open(mode='r')   Open file and return a file object.
   .file(mode='r')   Same.
   .bytes(mode='r')  Read the file in binary mode and return content as string.
 link.  .isfile() returns False for a special file.  To test a special file's
 type, pass .stat().st_mode to one of the S_*() functions in the 'stat' module;
 this is more efficient than .isspecial() when you only care about one type.
-                     
+
 Checking permissions and other information:
   .stat()         Get general file information; see os.stat().
   .lstat()        Same as .stat() but don't follow a symbolic link.
   .statvfs()      Get general information about the filesystem; see
                     os.statvfs().
   .samefile(other)  Is self and other the same file?  Returns True if one is
-                    a symbolic or hard link to the other.  'other' may be a 
+                    a symbolic or hard link to the other.  'other' may be a
                     path or a string.
   .pathconf(name) See os.pathconf(); OS-specific info about the path.
   .canread()      Can we read the file?  (JOP: no equivalent.)
   .canwrite()     Can we write the file? (JOP: no equivalent.)
   .canexecute()   Can we execute the file?  True for a directory means we
-                    can chdir into it or access its contents. 
+                    can chdir into it or access its contents.
                     (JOP: no equivalent.)
   .access(mode)   General permission test; see os.access() for usage.
 
                     'time' is either None to set them to the current time, or
                     a tuple of (atime, mtime) -- integers in tick
                     format (the same format returned by time.time()).
-  .getutime()     Return a tuple of (atime, mtime).  This can be passed 
+  .getutime()     Return a tuple of (atime, mtime).  This can be passed
                     directly to another path's .utime().  (JOP: no equiv.)
   .copyutimefrom(other)  Make my atime/mtime match the other path's.
                     'other' may be a path or a string.  (JOP: no equiv.)
   .grant(mode)    Subtract 'mode' from the file's current mode.  (Uses '&'.)
   .chown(uid=None, gid=None)  Change the path's owner/group.
                     If uid or gid is a string, look up the corresponding
-                    number via the 'pwd' or 'group' module.  
+                    number via the 'pwd' or 'group' module.
                     (JOP: both uid and gid must be specified, and both must
                     be numeric.)
-  .needsupdate(*other)  
+  .needsupdate(*other)
                   True if the path doesn't exist or its mtime is older
                     than any of the others.  If any 'other' is a directory,
                     only the directory mtime will be compared; this method
                     does not recurse.  A directory's mtime changes when a
-                    file in it is added, removed, or renamed.  To do the 
+                    file in it is added, removed, or renamed.  To do the
                     equvalent of iteration, see .iterneedsupdate().
                     (JOP: no equivalent method.)
-  .iterneedsupdate(iterpaths)  
+  .iterneedsupdate(iterpaths)
                   Same as .needsupdate() but use an iterable to
-                    specify the other paths.  To do the equivalent of a 
+                    specify the other paths.  To do the equivalent of a
                     recursive compare, call .walkfiles() on the other
-                    directories and concatenate the iterators using 
+                    directories and concatenate the iterators using
                     itertools.chain, interspersing any static lists of paths
                     you wish.  (JOP: no equivalent method.)
-                    
+
 Moving files and directories:
-  .move(dest, overwrite=True, prune=False, atomic=False)     
+  .move(dest, overwrite=True, prune=False, atomic=False)
                  Move the file or directory to 'dest'.
                     Tries os.rename() or os.renames() first, falls back to
                     shutil.move() if it fails.
                  it doesn't exist.  Convenient but dangerous!
                  (JOP: combines .rmtree(), .rmdir(), and .remove(), plus unqiue
                  features.)
-  .rmdir(prune=False)     
+  .rmdir(prune=False)
                Delete a directory.
                  Silently succeeds if it doesn't exist.  OSError if it's a file
-                 or symbolic link.  See .delete_dammit().  
+                 or symbolic link.  See .delete_dammit().
                  If 'prune' is true, also delete any empty ancestor
                  directories.
                  (JOP: equivalent to .removedirs() if prune is true, or
                  .rmdir() if prune is false, except the JOP methods don't have
                  a 'prune' argument, and they raise OSError if the directory
                  doesn't exist.)
-  .remove(prune=False)    
+  .remove(prune=False)
               Delete a file.
-                 Silently succeeds if it doesn't exist.  OSError if it's a 
+                 Silently succeeds if it doesn't exist.  OSError if it's a
                  directory.
                  If 'prune' is true, delete any ancestor directories.
                  (JOP: equivalent to .remove() if prune is false, except JOP
-                 method has no 'prune' arg.  Raises OSError if it doesn't 
+                 method has no 'prune' arg.  Raises OSError if it doesn't
                  exist.)
    .unlink(prune=False)  Same as .remove().
 
                  Create a symbolic link at 'source' pointing to this path.
                    If path is relative, it should be relative to source's
                    directory, but it needn't be valid with the current
-                   directory. 
+                   directory.
   .readlink()   Return the path this symbolic link points to.
   .readlinkabs()  Same as .readlink() but always return an absolute path.
 
                 Copy path's permission bits to dest (but not its content).
   .copystat(dest)
                 Copy path's permission bits and atime/mtime to dest (but not
-                  its content or owner/group).  Overlaps with .copyutimeto().  
+                  its content or owner/group).  Overlaps with .copyutimeto().
 
 Modifying the runtime environment:
-  .chdir(push=False)      
+  .chdir(push=False)
                 Set the current working directory to path.
                   If 'push' is true, push the old current directory onto
                   path.pushed_dirs (class attribute) and log a debug message.
 #     it doesn't play nice with other types that implement
 #     __radd__().  Test this.
 """
-import codecs, fnmatch, glob, os, shutil, stat, sys
-import tempfile as _tempfile # Avoid conflicts with same-name method.
+import codecs
+import fnmatch
+import glob
+import os
+import shutil
+import stat
+import sys
+import tempfile as _tempfile  # Avoid conflicts with same-name method.
 
 __version__ = '0.1'
 __all__ = ['path']
 _base = os.path.supports_unicode_filenames and unicode or str
 _textmode = hasattr(file, 'newlines') and 'U' or 'r'
 
+
 class path(_base):
     #### Constants
     # File types returned by .type() and accepted by .specials() and .find().
-    FILE   = 'f'
-    DIR    = 'd'
-    LINK   = 'l'
-    CHAR   = 'c'
-    BLOCK  = 'b'
-    PIPE   = 'p'
+    FILE = 'f'
+    DIR = 'd'
+    LINK = 'l'
+    CHAR = 'c'
+    BLOCK = 'b'
+    PIPE = 'p'
     SOCKET = 's'
-    DOOR   = 'D'
+    DOOR = 'D'
     SPECIAL_TYPES = [CHAR, BLOCK, PIPE, SOCKET, DOOR]
 
     #### Flags and other class attributes
     repr_as_str = False
-    pushed_dirs = [] # Shared list of pushed directories.
+    pushed_dirs = []  # Shared list of pushed directories.
 
     # --- Special Python methods.
 
         os.chdir(dir)
     popdir = classmethod(popdir)
 
-    def tempfile(klass, suffix='', prefix=_tempfile.template, dir=None, 
-        text=False):
+    def tempfile(klass, suffix='', prefix=_tempfile.template, dir=None,
+                 text=False):
         fil = _tempfile.mkstemp(suffix, prefix, dir, text)
         return klass(fil)
     tempfile = classmethod(tempfile)
         return klass(dir)
     tempdir = classmethod(tempdir)
 
-    def tempfileobject(mode='w+b', bufsize=-1, suffix='', 
-        prefix=_tempfile.template, dir=None):
+    def tempfileobject(mode='w+b', bufsize=-1, suffix='',
+                       prefix=_tempfile.template, dir=None):
         f = _tempfile.TemporaryFile(mode, bufsize, suffix, prefix, dir)
         return f
     tempfileobject = staticmethod(tempfileobject)
-
-
     # --- Operations on path strings.
 
-    def abspath(self):       return self.__class__(os.path.abspath(self))
-    def normcase(self):      return self.__class__(os.path.normcase(self))
-    def normpath(self):      return self.__class__(os.path.normpath(self))
-    def realpath(self):      return self.__class__(os.path.realpath(self))
-    def expanduser(self):    return self.__class__(os.path.expanduser(self))
-    def expandvars(self):    return self.__class__(os.path.expandvars(self))
-    def dirname(self):       return self.__class__(os.path.dirname(self))
+    def abspath(self):
+        return self.__class__(os.path.abspath(self))
+
+    def normcase(self):
+        return self.__class__(os.path.normcase(self))
+
+    def normpath(self):
+        return self.__class__(os.path.normpath(self))
+
+    def realpath(self):
+        return self.__class__(os.path.realpath(self))
+
+    def expanduser(self):
+        return self.__class__(os.path.expanduser(self))
+
+    def expandvars(self):
+        return self.__class__(os.path.expandvars(self))
+
+    def dirname(self):
+        return self.__class__(os.path.dirname(self))
     basename = os.path.basename
 
     def expand(self):
         dirname, None, None,
         """ This path's parent directory, as a new path object.
 
-        For example, path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib')
+        For example,
+        path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib')
         """)
 
     name = property(
         _get_base, None, None,
         """ The same as path.name, but with one file extension stripped off.
 
-        For example, path('/home/guido/python.tar.gz').name     == 'python.tar.gz',
-        but          path('/home/guido/python.tar.gz').namebase == 'python.tar'
+        For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz',
+        but path('/home/guido/python.tar.gz').namebase == 'python.tar'
         """)
 
     ext = property(
             msg = "path '%s' does not start with prefix '%s'" % (self, prefix)
             raise ValueError(msg)
         return newparent / self[len(prefix):]
-
-
     # --- Listing, searching, walking, and matching
 
     def listdir(self, pattern=None, symlinks=True, names_only=False):
 
         If 'symlinks' is false, exclude symbolic links from the result.
         """
-        
+
         return [p for p in self.listdir(pattern, symlinks) if p.isfile()]
 
     def symlinks(self, pattern=None):
         whose names match the given pattern.  For example,
         d.files('*.pyc').
         """
-        
+
         return [p for p in self.listdir(pattern, True) if p.islink()]
 
     def walk(self, pattern=None, symlinks=True):
                     cmd.extend([option, value])
         # One-arg options.
         for key in ['type', 'maxdepth', 'mindepth', 'newer', 'anewer',
-            'cnewer', 'empty', 'fstype', 'gid', 'group', 'iname', 'lname',
-            'ilname', 'inum', 'path', 'ipath', 'regex', 'iregex', 'links',
-            'perm', 'size', 'uid', 'user', 'xtype']:
+                    'cnewer', 'empty', 'fstype', 'gid', 'group', 'iname',
+                    'lname', 'ilname', 'inum', 'path', 'ipath', 'regex',
+                    'iregex', 'links', 'perm', 'size', 'uid', 'user', 'xtype']:
             if key in kw:
                 option = '-' + key
                 value = str(kw[key])
                     cmd.extend([option, str(value)])
         # No-arg options.
         for key in ['daystart', 'depth', 'follow', 'mount', 'xdev', 'noleaf',
-            'nouser', 'nogroup']:
-            if kw.get(key): # If key exists and value is true.
+                    'nouser', 'nogroup']:
+            if kw.get(key):  # If key exists and value is true.
                 option = '-' + key
                 cmd.append(option)
         if args:
         of all the files users have in their bin directories.
         """
         return map(path, glob.glob(_base(self / pattern)))
-
-
     # --- Reading or writing an entire file at once.
 
     def open(self, mode='r'):
         """ Open this file.  Return a file object. """
         return file(self, mode)
-        
+
     file = open
 
     def bytes(self):
                      .replace(u'\x85', u'\n')
                      .replace(u'\u2028', u'\n'))
 
-    def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False):
+    def write_text(self, text, encoding=None, errors='strict',
+                   linesep=os.linesep, append=False):
         """ Write the given text to this file.
 
         The default behavior is to overwrite any existing file;
                 f.write(line)
         finally:
             f.close()
-
-
     # --- Methods for querying the filesystem.
 
     exists = os.path.exists
             return self.PIPE
         elif stat.S_ISSOCK(mode):
             return self.SOCKET
-        return None 
-        
+        return None
+
     if hasattr(os.path, 'samefile'):
         samefile = os.path.samefile
 
     if hasattr(os, 'pathconf'):
         def pathconf(self, name):
             return os.pathconf(self, name)
-
-
     # --- Modifying operations on files and directories
 
     def utime(self, times):
         times = self.getutime()
         for other in iterpaths:
             other.utime(times)
+
     def chmod(self, mode):
         os.chmod(self, mode)
 
 
     def renames(self, new):
         os.renames(self, new)
-
-
     # --- Create/delete operations on directories
 
     def mkdir(self, mode=0777):
     def removedirs(self):
         if self.exists():
             os.removedirs(self)
-
-
     # --- Modifying operations on files
 
     def touch(self):
         if self.exists():
             os.unlink(self)
 
-
     # --- Links
-
     if hasattr(os, 'link'):
         def link(self, newpath):
             """ Create a hard link at 'newpath', pointing to this file. """
             else:
                 return (self.parent / p).abspath()
 
-
     # --- High-level functions from shutil
 
     copyfile = shutil.copyfile