Unipath-0.2.1/0000755000175000017500000000000011014371320011270 5ustar msomsoUnipath-0.2.1/unipath/0000755000175000017500000000000011014370755012753 5ustar msomsoUnipath-0.2.1/unipath/errors.py0000644000175000017500000000020011013773726014635 0ustar msomsoclass UnsafePathError(ValueError): pass class RecursionError(OSError): pass class DebugWarning(UserWarning): pass Unipath-0.2.1/unipath/path.py0000644000175000017500000002507311013773726014274 0ustar msomso"""unipath.py - A two-class approach to file/directory operations in Python. Full usage, documentation, changelog, and history are at http://sluggo.scrapping.cc/python/unipath/ (c) 2007 by Mike Orr (and others listed in "History" section of doc page). Permission is granted to redistribute, modify, and include in commercial and noncommercial products under the terms of the Python license (i.e., the "Python Software Foundation License version 2" at http://www.python.org/download/releases/2.5/license/). """ import errno import fnmatch import glob import os import shutil import stat import sys import time import warnings from unipath.abstractpath import AbstractPath from unipath.errors import RecursionError __all__ = ["Path"] #warnings.simplefilter("ignore", DebugWarning, append=1) def flatten(iterable): """Yield each element of 'iterable', recursively interpolating lists and tuples. Examples: [1, [2, 3], 4] => iter([1, 2, 3, 4]) [1, (2, 3, [4]), 5) => iter([1, 2, 3, 4, 5]) """ for elm in iterable: if isinstance(elm, (list, tuple)): for relm in flatten(elm): yield relm else: yield elm class Path(AbstractPath): ##### CURRENT DIRECTORY #### @classmethod def cwd(class_): """ Return the current working directory as a path object. """ return class_(os.getcwd()) def chdir(self): os.chdir(self) #### CALCULATING PATHS #### def absolute(self): """Return the absolute Path, prefixing the current directory if necessary. """ return self.__class__(os.path.abspath(self)) def relative(self): """Return a relative path to self from the current working directory. """ return self.__class__.cwd().rel_path_to(self) def rel_path_to(self, dst): """ Return a relative path from self to dst. This prefixes as many pardirs (``..``) as necessary to reach a common ancestor. If there's no common ancestor (e.g., they're are on different Windows drives), the path will be absolute. """ origin = self.__class__(self).absolute() if not origin.isdir(): origin = origin.parent dest = self.__class__(dst).absolute() orig_list = origin.norm_case().components() # Don't normcase dest! We want to preserve the case. dest_list = dest.components() if orig_list[0] != os.path.normcase(dest_list[0]): # Can't get here from there. return self.__class__(dest) # Find the location where the two paths start to differ. i = 0 for start_seg, dest_seg in zip(orig_list, dest_list): if start_seg != os.path.normcase(dest_seg): break i += 1 # Now i is the point where the two paths diverge. # Need a certain number of "os.pardir"s to work up # from the origin to the point of divergence. segments = [os.pardir] * (len(orig_list) - i) # Need to add the diverging part of dest_list. segments += dest_list[i:] if len(segments) == 0: # If they happen to be identical, use os.curdir. return self.__class__(os.curdir) else: newpath = os.path.join(*segments) return self.__class__(newpath) def resolve(self): """Return an equivalent Path that does not contain symbolic links.""" return self.__class__(os.path.realpath(self)) #### LISTING DIRECTORIES #### def listdir(self, pattern=None, filter=None, names_only=False): if names_only and filter is not None: raise TypeError("filter not allowed if 'names_only' is true") empty_path = self == "" if empty_path: names = os.listdir(os.path.curdir) else: names = os.listdir(self) if pattern is not None: names = fnmatch.filter(names, pattern) names.sort() if names_only: return names ret = [self.child(x) for x in names] if filter is not None: ret = [x for x in ret if filter(x)] return ret def walk(self, pattern=None, filter=None, top_down=True): return self._walk(pattern, filter, top_down, set()) def _walk(self, pattern, filter, top_down, seen): if not self.isdir(): raise RecursionError("not a directory: %s" % self) real_dir = self.resolve() if real_dir in seen: return # We've already recursed this directory. seen.add(real_dir) for child in self.listdir(pattern): is_dir = child.isdir() if is_dir and not top_down: for grandkid in child._walk(pattern, filter, top_down, seen): yield grandkid if filter is None or filter(child): yield child if is_dir and top_down: for grandkid in child._walk(pattern, filter, top_down, seen): yield grandkid #### STAT ATTRIBUTES #### exists = os.path.exists lexists = os.path.lexists isfile = os.path.isfile isdir = os.path.isdir islink = os.path.islink ismount = os.path.ismount atime = os.path.getatime ctime = os.path.getctime mtime = os.path.getmtime size = os.path.getsize if hasattr(os.path, 'samefile'): same_file = os.path.samefile # For some reason these functions have to be wrapped in methods. def stat(self): return os.stat(self) def lstat(self): return os.lstat(self) if hasattr(os, 'statvfs'): def statvfs(self): return os.statvfs(self) def chmod(self, mode): os.chmod(self, mode) if hasattr(os, 'chown'): def chown(self, uid, gid): os.chown(self, uid, gid) def set_times(self, mtime=None, atime=None): """Set a path's modification and access times. Times must be in ticks as returned by ``time.time()``. If 'mtime' is None, use the current time. If 'atime' is None, use 'mtime'. Creates an empty file if the path does not exists. On some platforms (Windows), the path must not be a directory. """ if not self.exists(): fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666) os.close(fd) if mtime is None: mtime = time.time() if atime is None: atime = mtime times = atime, mtime os.utime(self, times) #### CREATING, REMOVING, AND RENAMING #### def mkdir(self, parents=False, mode=0777): if self.exists(): return if parents: os.makedirs(self, mode) else: os.mkdir(self, mode) def rmdir(self, parents=False): if not self.exists(): return if parents: os.removedirs(self) else: os.rmdir(self) def remove(self): if self.exists(): os.remove(self) def rename(self, new, parents=False): if parents: os.renames(self, new) else: os.rename(self, new) #### SYMBOLIC AND HARD LINKS #### if hasattr(os, 'link'): def hardlink(self, newpath): """Create a hard link at 'newpath' pointing to self. """ os.link(self, newpath) if hasattr(os, 'symlink'): def write_link(self, link_content): """Create a symbolic link at self pointing to 'link_content'. This is the same as .symlink but with the args reversed. """ os.symlink(link_content, self) def make_relative_link_to(self, dest): """Make a relative symbolic link from self to dest. Same as self.write_link(self.rel_path_to(dest)) """ link_content = self.rel_path_to(dest) self.write_link(link_content) if hasattr(os, 'readlink'): def read_link(self, absolute=False): p = self.__class__(os.readlink(self)) if absolute and not p.isabsolute(): p = self.__class__(self.parent, p) return p #### HIGH-LEVEL OPERATIONS #### def copy(self, dst, times=False, perms=False): """Copy the file, optionally copying the permission bits (mode) and last access/modify time. If the destination file exists, it will be replaced. Raises OSError if the destination is a directory. If the platform does not have the ability to set the permission or times, ignore it. This is shutil.copyfile plus bits of shutil.copymode and shutil.copystat's implementation. shutil.copy and shutil.copy2 are not supported but are easy to do. """ shutil.copyfile(self, dst) if times or perms: self.copy_stat(dst, times, perms) def copy_stat(self, dst, times=True, perms=True): st = os.stat(self) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): m = stat.S_IMODE(st.st_mode) os.chmod(dst, m) def copy_tree(dst, perserve_symlinks=False, times=False, perms=False): raise NotImplementedError() if hasattr(shutil, 'move'): move = shutil.move def needs_update(self, others): if not self.exists(): return True control = self.mtime() for p in flatten(others): if p.isdir(): for child in p.walk(filter=FILES): if child.mtime() > control: return True elif p.mtime() > control: return True return False def read_file(self, mode="rU"): f = open(self, mode) content = f.read() f.close() return content def rmtree(self, parents=False): """Delete self recursively, whether it's a file or directory. directory, remove it recursively (same as shutil.rmtree). If it doesn't exist, do nothing. If you're looking for a 'rmtree' method, this is what you want. """ if self.isfile(): os.remove(self) elif self.isdir(): shutil.rmtree(self) if not parents: return p = self.parent while p: try: os.rmdir(p) except os.error: break p = p.parent def write_file(self, content, mode="w"): f = open(self, mode) f.write(content) f.close() Unipath-0.2.1/unipath/tools.py0000755000175000017500000000155011013773726014475 0ustar msomso"""Convenience functions. """ import sys # Package imports. from unipath import Path, FSPath def dict2dir(dir, dic, mode="w"): dir = FSPath(dir) if not dir.exists(): dir.mkdir() for filename, content in dic.iteritems(): p = FSPath(dir, filename) if isinstance(content, dict): dict2dir(p, content) continue f = open(p, mode) f.write(content) f.close() def dump_path(path, prefix="", tab=" ", file=None): if file is None: file = sys.stdout p = Path(path) if p.islink(): print >>file, "%s%s -> %s" % (prefix, p.name, p.read_link()) elif p.isdir(): print >>file, "%s%s:" % (prefix, p.name) for p2 in p.listdir(): dump_path(p2, prefix+tab, tab, file) else: print >>file, "%s%s (%d)" % (prefix, p.name, p.size()) Unipath-0.2.1/unipath/__init__.py0000644000175000017500000000163111013773726015071 0ustar msomso"""unipath.py - A two-class approach to file/directory operations in Python. Full usage, documentation, changelog, and history are at http://sluggo.scrapping.cc/python/unipath/ (c) 2007 by Mike Orr (and others listed in "History" section of doc page). Permission is granted to redistribute, modify, and include in commercial and noncommercial products under the terms of the Python license (i.e., the "Python Software Foundation License version 2" at http://www.python.org/download/releases/2.5/license/). """ from unipath.abstractpath import AbstractPath from unipath.path import Path FSPath = Path #### FILTER FUNCTIONS (PUBLIC) #### def DIRS(p): return p.isdir() def FILES(p): return p.isfile() def LINKS(p): return p.islink() def DIRS_NO_LINKS(p): return p.isdir() and not p.islink() def FILES_NO_LINKS(p): return p.isfile() and not p.islink() def DEAD_LINKS(p): return p.islink() and not p.exists() Unipath-0.2.1/unipath/abstractpath.py0000644000175000017500000002072511013773726016017 0ustar msomso"""unipath.py - A two-class approach to file/directory operations in Python. Full usage, documentation, changelog, and history are at http://sluggo.scrapping.cc/python/unipath/ (c) 2007 by Mike Orr (and others listed in "History" section of doc page). Permission is granted to redistribute, modify, and include in commercial and noncommercial products under the terms of the Python license (i.e., the "Python Software Foundation License version 2" at http://www.python.org/download/releases/2.5/license/). """ import os from unipath.errors import UnsafePathError __all__ = ["AbstractPath"] # Use unicode strings if possible _base = os.path.supports_unicode_filenames and unicode or str class AbstractPath(_base): """An object-oriented approach to os.path functions.""" pathlib = os.path auto_norm = False #### Special Python methods. def __new__(class_, *args, **kw): norm = kw.pop("norm", None) if norm is None: norm = class_.auto_norm if kw: kw_str = ", ".join(kw.iterkeys()) raise TypeError("unrecognized keyword args: %s" % kw_str) newpath = class_._new_helper(args) if isinstance(newpath, class_): return newpath if norm: newpath = class_.pathlib.normpath(newpath) # Can't call .norm() because the path isn't instantiated yet. return _base.__new__(class_, newpath) def __add__(self, more): try: resultStr = _base.__add__(self, more) except TypeError: #Python bug resultStr = NotImplemented if resultStr is NotImplemented: return resultStr return self.__class__(resultStr) @classmethod def _new_helper(class_, args): pathlib = class_.pathlib # If no args, return "." or platform equivalent. if not args: return pathlib.curdir # Avoid making duplicate instances of the same immutable path if len(args) == 1 and isinstance(args[0], class_) and \ args[0].pathlib == pathlib: return args[0] legal_arg_types = (class_, basestring, list, int, long) args = list(args) for i, arg in enumerate(args): if not isinstance(arg, legal_arg_types): m = "arguments must be str, unicode, list, int, long, or %s" raise TypeError(m % class_.__name__) if isinstance(arg, (int, long)): args[i] = str(arg) elif isinstance(arg, class_) and arg.pathlib != pathlib: arg = getattr(arg, components)() # Now a list. if arg[0]: reason = ("must use a relative path when converting " "from '%s' platform to '%s': %s") tup = arg.pathlib.__name__, pathlib.__name__, arg raise ValueError(reason % tup) # Fall through to convert list of components. if isinstance(arg, list): args[i] = pathlib.join(*arg) return pathlib.join(*args) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, _base(self)) def norm(self): return self.__class__(self.pathlib.normpath(self)) def expand_user(self): return self.__class__(self.pathlib.expanduser(self)) def expand_vars(self): return self.__class__(self.pathlib.expandvars(self)) def expand(self): """ Clean up a filename by calling expandvars(), expanduser(), and norm() on it. This is commonly everything needed to clean up a filename read from a configuration file, for example. """ newpath = self.pathlib.expanduser(self) newpath = self.pathlib.expandvars(newpath) newpath = self.pathlib.normpath(newpath) return self.__class__(newpath) #### Properies: parts of the path. @property def parent(self): """The path without the final component; akin to os.path.dirname(). Example: Path('/usr/lib/libpython.so').parent => Path('/usr/lib') """ return self.__class__(self.pathlib.dirname(self)) @property def name(self): """The final component of the path. Example: path('/usr/lib/libpython.so').name => Path('libpython.so') """ return self.__class__(self.pathlib.basename(self)) @property def stem(self): """Same as path.name but with one file extension stripped off. Example: path('/home/guido/python.tar.gz').stem => Path('python.tar') """ return self.__class__(self.pathlib.splitext(self.name)[0]) @property def ext(self): """The file extension, for example '.py'.""" return self.__class__(self.pathlib.splitext(self)[1]) #### Methods to extract and add parts to the path. def split_root(self): """Split a path into root and remainder. The root is always "/" for posixpath, or a backslash-root, drive-root, or UNC-root for ntpath. If the path begins with none of these, the root is returned as "" and the remainder is the entire path. """ P = self.__class__ if hasattr(self.pathlib, "splitunc"): root, rest = self.pathlib.splitunc(self) if root: if rest.startswith(self.pathlib.sep): root += self.pathlib.sep rest = rest[len(self.pathlib.sep):] return P(root), P(rest) # @@MO: Should test altsep too. root, rest = self.pathlib.splitdrive(self) if root: if rest.startswith(self.pathlib.sep): root += self.pathlib.sep rest = rest[len(self.pathlib.sep):] return P(root), P(rest) # @@MO: Should test altsep too. if self.startswith(self.pathlib.sep): return P(self.pathlib.sep), P(rest[len(self.pathlib.sep):]) if self.pathlib.altsep and self.startswith(self.pathlib.altsep): return P(self.pathlib.altsep), P(rest[len(self.pathlib.altsep):]) return P(""), self def components(self): # @@MO: Had to prevent "" components from being appended. I don't # understand why Lindqvist didn't have this problem. # Also, doesn't this fail to get the beginning components if there's # a "." or ".." in the middle of the path? root, loc = self.split_root() components = [] while loc != self.pathlib.curdir and loc != self.pathlib.pardir: prev = loc loc, child = self.pathlib.split(prev) #print "prev=%r, loc=%r, child=%r" % (prev, loc, child) if loc == prev: break if child != "": components.append(child) if loc == "": break if loc != "": components.append(loc) components.reverse() components.insert(0, root) return [self.__class__(x) for x in components] def ancestor(self, n): p = self for i in range(n): p = p.parent return p def child(self, *children): # @@MO: Compare against Glyph's method. for child in children: if self.pathlib.sep in child: msg = "arg '%s' contains path separator '%s'" tup = child, self.pathlib.sep raise UnsafePathError(msg % tup) if self.pathlib.altsep and self.pathlib.altsep in child: msg = "arg '%s' contains alternate path separator '%s'" tup = child, self.pathlib.altsep raise UnsafePathError(msg % tup) if child == self.pathlib.pardir: msg = "arg '%s' is parent directory specifier '%s'" tup = child, self.pathlib.pardir raise UnsafePathError(msg % tup) if child == self.pathlib.curdir: msg = "arg '%s' is current directory specifier '%s'" tup = child, self.pathlib.curdir raise UnsafePathError(msg % tup) newpath = self.pathlib.join(self, *children) return self.__class__(newpath) def norm_case(self): return self.__class__(self.pathlib.normcase(self)) def isabsolute(self): """True if the path is absolute. Note that we consider a Windows drive-relative path ("C:foo") absolute even though ntpath.isabs() considers it relative. """ return bool(self.split_root()[0]) Unipath-0.2.1/unipath/test.py0000755000175000017500000004627711014370755014327 0ustar msomso#!/usr/bin/env python """Unit tests for unipath.py and unipath_purist.py Environment variables: DUMP : List the contents of test direcories after each test. NO_CLEANUP : Don't delete test directories. (These are not command-line args due to the difficulty of merging my args with unittest's.) IMPORTANT: Tests may not assume what the current directory is because the tests may have been started from anywhere, and some tests chdir to the temprorary test directory which is then deleted. """ import ntpath import os import posixpath import tempfile import time import sys from nose.tools import eq_, raises # Package imports from unipath import * from unipath.errors import * from unipath.tools import dict2dir, dump_path AbstractPath.auto_norm = False class PosixPath(AbstractPath): pathlib = posixpath class NTPath(AbstractPath): pathlib = ntpath # Global flags cleanup = not bool(os.environ.get("NO_CLEANUP")) dump = bool(os.environ.get("DUMP")) def r(exception, func, *args, **kw): """This is supposed to exist in nose.tools as assert_raises(), but it doesn't. """ try: func(*args, **kw) except exception: pass except Exception, e: tup = exception.__name__, e.__class__.__name__, e raise AssertionError("expected %s, caught %s: %s" % tup) else: raise AssertionError("function didn't raise %s" % exception.__name__) class TestPathConstructor(object): def test_posix(self): eq_(str(PosixPath()), posixpath.curdir) eq_(str(PosixPath("foo/bar.py")), "foo/bar.py") eq_(str(PosixPath("foo", "bar.py")), "foo/bar.py") eq_(str(PosixPath("foo", "bar", "baz.py")), "foo/bar/baz.py") eq_(str(PosixPath("foo", PosixPath("bar", "baz.py"))), "foo/bar/baz.py") eq_(str(PosixPath("foo", ["", "bar", "baz.py"])), "foo/bar/baz.py") eq_(str(PosixPath("")), "") eq_(str(PosixPath()), ".") eq_(str(PosixPath("foo", 1, "bar")), "foo/1/bar") def test_nt(self): eq_(str(NTPath()), ntpath.curdir) eq_(str(NTPath(r"foo\bar.py")), r"foo\bar.py") eq_(str(NTPath("foo", "bar.py")), r"foo\bar.py") eq_(str(NTPath("foo", "bar", "baz.py")), r"foo\bar\baz.py") eq_(str(NTPath("foo", NTPath("bar", "baz.py"))), r"foo\bar\baz.py") eq_(str(NTPath("foo", ["", "bar", "baz.py"])), r"foo\bar\baz.py") eq_(str(PosixPath("")), "") eq_(str(NTPath()), ".") eq_(str(NTPath("foo", 1, "bar")), r"foo\1\bar") class TestNorm(object): def test_posix(self): eq_(PosixPath("a//b/../c").norm(), "a/c") eq_(PosixPath("a/./b").norm(), "a/b") eq_(PosixPath("a/./b", norm=True), "a/b") eq_(PosixPath("a/./b", norm=False), "a/./b") class AutoNormPath(PosixPath): auto_norm = True eq_(AutoNormPath("a/./b"), "a/b") eq_(AutoNormPath("a/./b", norm=True), "a/b") eq_(AutoNormPath("a/./b", norm=False), "a/./b") def test_nt(self): eq_(NTPath(r"a\\b\..\c").norm(), r"a\c") eq_(NTPath(r"a\.\b").norm(), r"a\b") eq_(NTPath("a\\.\\b", norm=True), "a\\b") eq_(NTPath("a\\.\\b", norm=False), "a\\.\\b") class AutoNormPath(NTPath): auto_norm = True eq_(AutoNormPath("a\\.\\b"), "a\\b") eq_(AutoNormPath("a\\.\\b", norm=True), "a\\b") eq_(AutoNormPath("a\\.\\b", norm=False), "a\\.\\b") class TestAbstractPath(object): def test_repr(self): eq_(repr(Path("la_la_la")), "Path('la_la_la')") eq_(repr(NTPath("la_la_la")), "NTPath('la_la_la')") # Not testing expand_user, expand_vars, or expand: too dependent on the # OS environment. def test_properties(self): p = PosixPath("/first/second/third.jpg") eq_(p.parent, "/first/second") eq_(p.name, "third.jpg") eq_(p.ext, ".jpg") eq_(p.stem, "third") def test_properties2(self): # Usage sample in README is based on this. p = PosixPath("/usr/lib/python2.5/gopherlib.py") eq_(p.parent, Path("/usr/lib/python2.5")) eq_(p.name, Path("gopherlib.py")) eq_(p.ext, ".py") eq_(p.stem, Path("gopherlib")) q = PosixPath(p.parent, p.stem + p.ext) eq_(q, p) def test_split_root(self): eq_(PosixPath("foo/bar.py").split_root(), ("", "foo/bar.py")) eq_(PosixPath("/foo/bar.py").split_root(), ("/", "foo/bar.py")) eq_(NTPath("foo\\bar.py").split_root(), ("", "foo\\bar.py")) eq_(NTPath("\\foo\\bar.py").split_root(), ("\\", "foo\\bar.py")) eq_(NTPath("C:\\foo\\bar.py").split_root(), ("C:\\", "foo\\bar.py")) eq_(NTPath("C:foo\\bar.py").split_root(), ("C:", "foo\\bar.py")) eq_(NTPath("\\\\share\\base\\foo\\bar.py").split_root(), ("\\\\share\\base\\", "foo\\bar.py")) def test_split_root_vs_isabsolute(self): assert not PosixPath("a/b/c").isabsolute() assert not PosixPath("a/b/c").split_root()[0] assert PosixPath("/a/b/c").isabsolute() assert PosixPath("/a/b/c").split_root()[0] assert not NTPath("a\\b\\c").isabsolute() assert not NTPath("a\\b\\c").split_root()[0] assert NTPath("\\a\\b\\c").isabsolute() assert NTPath("\\a\\b\\c").split_root()[0] assert NTPath("C:\\a\\b\\c").isabsolute() assert NTPath("C:\\a\\b\\c").split_root()[0] assert NTPath("C:a\\b\\c").isabsolute() assert NTPath("C:a\\b\\c").split_root()[0] assert NTPath("\\\\share\\b\\c").isabsolute() assert NTPath("\\\\share\\b\\c").split_root()[0] def test_components(self): P = PosixPath eq_(P("a").components(), [P(""), P("a")]) eq_(P("a/b/c").components(), [P(""), P("a"), P("b"), P("c")]) eq_(P("/a/b/c").components(), [P("/"), P("a"), P("b"), P("c")]) P = NTPath eq_(P("a\\b\\c").components(), [P(""), P("a"), P("b"), P("c")]) eq_(P("\\a\\b\\c").components(), [P("\\"), P("a"), P("b"), P("c")]) eq_(P("C:\\a\\b\\c").components(), [P("C:\\"), P("a"), P("b"), P("c")]) eq_(P("C:a\\b\\c").components(), [P("C:"), P("a"), P("b"), P("c")]) eq_(P("\\\\share\\b\\c").components(), [P("\\\\share\\b\\"), P("c")]) def test_child(self): PosixPath("foo/bar").child("baz") r(UnsafePathError, PosixPath("foo/bar").child, "baz/fred") r(UnsafePathError, PosixPath("foo/bar").child, "..", "baz") r(UnsafePathError, PosixPath("foo/bar").child, ".", "baz") class TestStringMethods(object): def test_add(self): P = PosixPath eq_(P("a") + P("b"), P("ab")) eq_(P("a") + "b", P("ab")) eq_("a" + P("b"), P("ab")) class FilesystemTest(object): TEST_HIERARCHY = { "a_file": "Nothing important.", "animals": { "elephant": "large", "gonzo": "unique", "mouse": "small"}, "images": { "image1.gif": "", "image2.jpg": "", "image3.png": ""}, "swedish": { "chef": { "bork": { "bork": "bork!"}}}, } def setUp(self): self.d = d = Path(tempfile.mkdtemp()) dict2dir(d, self.TEST_HIERARCHY) self.a_file = Path(d, "a_file") self.animals = Path(d, "animals") self.images = Path(d, "images") self.chef = Path(d, "swedish", "chef", "bork", "bork") if hasattr(self.d, "write_link"): self.link_to_chef_file = Path(d, "link_to_chef_file") self.link_to_chef_file.write_link(self.chef) self.link_to_images_dir = Path(d, "link_to_images_dir") self.link_to_images_dir.write_link(self.images) self.dead_link = self.d.child("dead_link") self.dead_link.write_link("nowhere") self.missing = Path(d, "MISSING") self.d.chdir() def tearDown(self): d = self.d d.parent.chdir() # Always need a valid curdir to avoid OSErrors. if dump: dump_path(d) if cleanup: d.rmtree() if d.exists(): raise AssertionError("unable to delete temp dir %s" % d) else: print "Not deleting test directory", d class TestCalculatingPaths(FilesystemTest): def test_inheritance(self): assert Path.cwd().name # Can we access the property? def test_cwd(self): eq_(str(Path.cwd()), os.getcwd()) def test_chdir_absolute_relative(self): save_dir = Path.cwd() self.d.chdir() eq_(Path.cwd(), self.d) eq_(Path("swedish").absolute(), Path(self.d, "swedish")) save_dir.chdir() eq_(Path.cwd(), save_dir) def test_chef(self): p = Path(self.d, "swedish", "chef", "bork", "bork") eq_(p.read_file(), "bork!") def test_absolute(self): p1 = Path("images").absolute() p2 = self.d.child("images") eq_(p1, p2) def test_relative(self): p = self.d.child("images").relative() eq_(p, "images") def test_resolve(self): p1 = Path(self.link_to_images_dir, "image3.png") p2 = p1.resolve() eq_(p1.components()[-2:], ["link_to_images_dir", "image3.png"]) eq_(p2.components()[-2:], ["images", "image3.png"]) assert p1.exists() assert p2.exists() assert p1.same_file(p2) assert p2.same_file(p1) class TestRelPathTo(FilesystemTest): def test1(self): p1 = Path("animals", "elephant") p2 = Path("animals", "mouse") eq_(p1.rel_path_to(p2), Path("mouse")) def test2(self): p1 = Path("animals", "elephant") p2 = Path("images", "image1.gif") eq_(p1.rel_path_to(p2), Path(os.path.pardir, "images", "image1.gif")) def test3(self): p1 = Path("animals", "elephant") eq_(p1.rel_path_to(self.d), Path(os.path.pardir)) def test3(self): p1 = Path("swedish", "chef") eq_(p1.rel_path_to(self.d), Path(os.path.pardir, os.path.pardir)) class TestListingDirectories(FilesystemTest): def test_listdir_names_only(self): result = self.images.listdir(names_only=True) control = ["image1.gif", "image2.jpg", "image3.png"] eq_(result, control) def test_listdir_arg_errors(self): r(TypeError, self.d.listdir, filter=FILES, names_only=True) def test_listdir(self): result = Path("images").listdir() control = [ Path("images", "image1.gif"), Path("images", "image2.jpg"), Path("images", "image3.png")] eq_(result, control) def test_listdir_all(self): result = Path("").listdir() control = [ "a_file", "animals", "dead_link", "images", "link_to_chef_file", "link_to_images_dir", "swedish", ] eq_(result, control) def test_listdir_files(self): result = Path("").listdir(filter=FILES) control = [ "a_file", "link_to_chef_file", ] eq_(result, control) def test_listdir_dirs(self): result = Path("").listdir(filter=DIRS) control = [ "animals", "images", "link_to_images_dir", "swedish", ] eq_(result, control) def test_listdir_links(self): if not hasattr(self.d, "symlink"): return result = Path("").listdir(filter=LINKS) control = [ "dead_link", "link_to_chef_file", "link_to_images_dir", ] eq_(result, control) def test_listdir_files_no_links(self): result = Path("").listdir(filter=FILES_NO_LINKS) control = [ "a_file", ] eq_(result, control) def test_listdir_dirs_no_links(self): result = Path("").listdir(filter=DIRS_NO_LINKS) control = [ "animals", "images", "swedish", ] eq_(result, control) def test_listdir_dead_links(self): result = Path("").listdir(filter=DEAD_LINKS) control = [ "dead_link", ] eq_(result, control) def test_listdir_pattern_names_only(self): result = self.images.name.listdir("*.jpg", names_only=True) control = ["image2.jpg"] eq_(result, control) def test_listdir_pattern(self): result = self.images.name.listdir("*.jpg") control = [Path("images", "image2.jpg")] eq_(result, control) def test_walk(self): result = list(self.d.walk()) control = [ Path(self.a_file), Path(self.animals), Path(self.animals, "elephant"), Path(self.animals, "gonzo"), Path(self.animals, "mouse"), ] result = result[:len(control)] eq_(result, control) def test_walk_bottom_up(self): result = list(self.d.walk(top_down=False)) control = [ Path(self.a_file), Path(self.animals, "elephant"), Path(self.animals, "gonzo"), Path(self.animals, "mouse"), Path(self.animals), ] result = result[:len(control)] eq_(result, control) def test_walk_files(self): result = list(self.d.walk(filter=FILES)) control = [ Path(self.a_file), Path(self.animals, "elephant"), Path(self.animals, "gonzo"), Path(self.animals, "mouse"), Path(self.images, "image1.gif"), ] result = result[:len(control)] eq_(result, control) def test_walk_dirs(self): result = list(self.d.walk(filter=DIRS)) control = [ Path(self.animals), Path(self.images), Path(self.link_to_images_dir), Path(self.d, "swedish"), ] result = result[:len(control)] eq_(result, control) def test_walk_links(self): result = list(self.d.walk(filter=LINKS)) control = [ Path(self.dead_link), Path(self.link_to_chef_file), Path(self.link_to_images_dir), ] result = result[:len(control)] eq_(result, control) class TestStatAttributes(FilesystemTest): def test_exists(self): assert self.a_file.exists() assert self.images.exists() assert self.link_to_chef_file.exists() assert self.link_to_images_dir.exists() assert not self.dead_link.exists() assert not self.missing.exists() def test_lexists(self): assert self.a_file.lexists() assert self.images.lexists() assert self.link_to_chef_file.lexists() assert self.link_to_images_dir.lexists() assert self.dead_link.lexists() assert not self.missing.lexists() def test_isfile(self): assert self.a_file.isfile() assert not self.images.isfile() assert self.link_to_chef_file.isfile() assert not self.link_to_images_dir.isfile() assert not self.dead_link.isfile() assert not self.missing.isfile() def test_isdir(self): assert not self.a_file.isdir() assert self.images.isdir() assert not self.link_to_chef_file.isdir() assert self.link_to_images_dir.isdir() assert not self.dead_link.isdir() assert not self.missing.isdir() def test_islink(self): assert not self.a_file.islink() assert not self.images.islink() assert self.link_to_chef_file.islink() assert self.link_to_images_dir.islink() assert self.dead_link.islink() assert not self.missing.islink() def test_ismount(self): # Can't test on a real mount point because we don't know where it is assert not self.a_file.ismount() assert not self.images.ismount() assert not self.link_to_chef_file.ismount() assert not self.link_to_images_dir.ismount() assert not self.dead_link.ismount() assert not self.missing.ismount() def test_times(self): assert self.a_file.atime(), 50000 assert self.a_file.ctime(), 50000 assert self.a_file.mtime(), 50000 def test_size(self): eq_(self.chef.size(), 5) def test_same_file(self): if hasattr(self.a_file, "same_file"): control = Path(self.d, "a_file") assert self.a_file.same_file(control) assert not self.a_file.same_file(self.chef) def test_stat(self): st = self.chef.stat() assert hasattr(st, "st_mode") def test_statvfs(self): if hasattr(self.images, "statvfs"): stv = self.images.statvfs() assert hasattr(stv, "f_files") def test_chmod(self): self.a_file.chmod(0600) newmode = self.a_file.stat().st_mode eq_(newmode & 0777, 0600) # Can't test chown: requires root privilege and knowledge of local users. def set_times(self): self.a_file.set_times() self.a_file.set_times(50000) self.a_file.set_times(50000, 60000) class TestCreateRenameRemove(FilesystemTest): def test_mkdir_and_rmdir(self): self.missing.mkdir() assert self.missing.isdir() self.missing.rmdir() assert not self.missing.exists() def test_mkdir_and_rmdir_with_parents(self): abc = Path(self.d, "a", "b", "c") abc.mkdir(parents=True) assert abc.isdir() abc.rmdir(parents=True) assert not Path(self.d, "a").exists() def test_remove(self): self.a_file.remove() assert not self.a_file.exists() self.missing.remove() # Removing a nonexistent file should succeed. def test_rename(self): a_file = self.a_file b_file = Path(a_file.parent, "b_file") a_file.rename(b_file) assert not a_file.exists() assert b_file.exists() def test_rename_with_parents(self): pass # @@MO: Write later. class TestLinks(FilesystemTest): # @@MO: Write test_hardlink, test_symlink, test_write_link later. def test_read_link(self): eq_(self.dead_link.read_link(), "nowhere") class TestHighLevel(FilesystemTest): def test_copy(self): a_file = self.a_file b_file = Path(a_file.parent, "b_file") a_file.copy(b_file) assert b_file.exists() a_file.copy_stat(b_file) def test_copy_tree(self): return # .copy_tree() not implemented. images = self.images images2 = Path(self.images.parent, "images2") images.copy_tree(images2) def test_move(self): a_file = self.a_file b_file = Path(a_file.parent, "b_file") a_file.move(b_file) assert not a_file.exists() assert b_file.exists() def test_needs_update(self): control_files = self.images.listdir() self.a_file.set_times() assert not self.a_file.needs_update(control_files) time.sleep(1) control = Path(self.images, "image2.jpg") control.set_times() result = self.a_file.needs_update(self.images.listdir()) assert self.a_file.needs_update(control_files) def test_read_file(self): eq_(self.chef.read_file(), "bork!") # .write_file and .rmtree tested in .setUp. Unipath-0.2.1/README.txt0000644000175000017500000011767511013773726013026 0ustar msomsoUNIPATH %%%%%%% An object-oriented approach to file/directory operations ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :Version: 0.2.0 (2008-05-17) :Home page: http://sluggo.scrapping.cc/python/unipath/ :Author: Mike Orr :License: Python (http://www.python.org/psf/license) :Based on: See HISTORY section below. .. To format this document as HTML: rst2html.py README.txt README.html .. contents:: Introduction ============ Unipath is an object-oriented front end to the file/directory functions scattered throughout several Python library modules. It's based on Jason Orendorff's *path.py* but does not adhere as strictly to the underlying functions' syntax, in order to provide more user convenience and higher-level functionality. It comes with a test suite. .. important:: Changes for Unipath 0.1.0 users ``Path`` has been renamed to ``AbstractPath``, and ``FSPath`` to ``Path``. ``FSPath`` remains as an alias for backward compatibility. ``Path.symlink()`` is gone; use ``Path.write_link()`` instead. (Note that the argument order is the opposite.) See CHANGES.txt for the complete list of changes. The ``Path`` class encapsulates the file/directory operations in Python's ``os``, ``os.path``, and ``shutil`` modules. Its superclass ``AbstractPath`` class encapsulates those operations which aren't dependent on the filesystem. This is mainly an academic distinction to keep the code clean. Since ``Path`` can do everything ``AbstractPath`` does, most users just use ``Path``. The API has been streamlined to focus on what the application developer wants to do rather than on the lowest-level operations; e.g., ``.mkdir()`` succeeds silently if the directory already exists, and ``.rmtree()`` doesn't barf if the target is a file or doesn't exist. This allows the developer to write simple calls that "just work" rather than entire if-stanzas to handle low-level details s/he doesn't care about. This makes applications more self-documenting and less cluttered. Convenience methods: * ``.read_file`` and ``.write_file`` encapsulate the open/read/close pattern. * ``.needs_update(others)`` tells whether the path needs updating; i.e., if it doesn't exist or is older than any of the other paths. * ``.ancestor(N)`` returns the Nth parent directory, useful for joining paths. * ``.child(\*components)`` is a "safe" version of join. * ``.split_root()`` handles slash/drive/UNC absolute paths in a uniform way. - Optional high-level functions in the ``unipath.tools`` module. - For Python >= 2.4 - Path objects are immutable so can be used as dictionary keys. Sample usage for pathname manipulation:: >>> from unipath import Path >>> p = Path("/usr/lib/python2.5/gopherlib.py") >>> p.parent Path("/usr/lib/python2.5") >>> p.name Path("gopherlib.py") >>> p.ext '.py' >>> p.stem Path('gopherlib') >>> q = Path(p.parent, p.stem + p.ext) >>> q Path('/usr/lib/python2.5/gopherlib.py') >>> q == p True Sample usage for filesystem access:: >>> import tempfile >>> from unipath import Path >>> d = Path(tempfile.mkdtemp()) >>> d.isdir() True >>> p = Path(d, "sample.txt") >>> p.exists() False >>> p.write_file("The king is a fink!") >>> p.exists() True >>> print p.read_file() The king is a fink! >>> d.rmtree() >>> p.exists() False The name "Unipath" is short for "universal path", as it grew out of a discussion on python-dev about the ideal path API for Python. Unipath's API is mostly stable but there's no guarantee it won't change in future versions. Installation and testing ======================== If you have EasyInstall, run "easy_install unipath". Otherwise unpack the source and run "python setup.py install" in the top-level directory. You can also copy the "unipath" directory to somewhere on your Python path. To test the library you'll need the Nose package. cd to the top-level directory and run "python unipath/test.py". Path and AbstractPath objects ============================= Constructor ----------- ``Path`` (and ``AbstractPath``) objects can be created from a string path, or from several string arguments which are joined together a la ``os.path.join``. Each argument can be a string, an ``(Abstract)Path`` instance, an int or long, or a list/tuple of strings to be joined:: p = Path("foo/bar.py") # A relative path p = Path("foo", "bar.py") # Same as previous p = Path(["foo", "bar.py"]) # Same as previous p = Path("/foo", "bar", "baz.py") # An absolute path: /foo/bar/baz.py p = Path("/foo", Path("bar/baz.py")) # Same as previous p = Path("/foo", ["", "bar", "baz.py"]) # Embedded Path.components() result p = Path("record", 123) # Same as Path("record/123") p = Path("") # An empty path p = Path() # Same as Path(os.curdir) To get the actual current directory, use ``Path.cwd()``. (This doesn't work with ``AbstractPath``, of course. Adding two paths results in a concatenated path. The other string methods return strings, so you'll have to wrap them in ``Path`` to make them paths again. A future version will probably override these methods to return paths. Multiplying a path returns a string, as if you'd ever want to do that. Normalization ------------- The new path is normalized to clean up redundant ".." and "." in the middle, double slashes, wrong-direction slashes, etc. On case-insensitive filesystems it also converts uppercase to lowercase. This is all done via ``os.path.normpath()``. Here are some examples of normalizations:: a//b => a/b a/../b => b a/./b => a/b a/b => a\\b # On NT. a\\b.JPG => a\\b.jpg # On NT. If the actual filesystem path contains symbolic links, normalizing ".." goes to the parent of the symbolic link rather than to the parent of the linked-to file. For this reason, and because there may be other cases where normalizing produces the wrong path, you can disable automatic normalization by setting the ``.auto_norm`` class attribute to false. I'm not sure whether Unipath should normalize by default, so if you care one way or the other you should explicitly set it at the beginning of your application. You can override the auto_norm setting by passing "norm=True" or "norm=False" as a keyword argument to the constructor. You can also call ``.norm()`` anytime to manually normalize the path. Properties ---------- Path objects have the following properties: .parent The path without the final component. .name The final component only. .ext The last part of the final component beginning with a dot (e.g., ".gz"), or "" if there is no dot. This is also known as the extension. .stem The final component without the extension. Examples are given in the first sample usage above. Methods ------- Path objects have the following methods: .ancestor(N) Same as specifying ``.parent`` N times. .child(\*components) Join paths in a safe manner. The child components may not contain a path separator or be curdir or pardir ("." or ".." on Posix). This is to prevent untrusted arguments from creating a path above the original path's directory. .components() Return a list of directory components as strings. The first component will be the root ("/" on Posix, a Windows drive root, or a UNC share) if the path is absolute, or "" if it's relative. Calling ``Path(components)``, ``Path(*components)``, or ``os.path.join(*components)`` will recreate the original path. .expand() Same as ``p.expand_user().expand_vars().norm()``. Usually this is all you need to fix up a path read from a config file. .expand_user() Interpolate "~" and "~user" if the platform allows, and return a new path. .expand_vars() Interpolate environment variables like "$BACKUPS" if the platform allows, and return a new path. .isabsolute() Is the path absolute? .norm() See Normalization above. Same as ``os.path.normpath``. .norm_case() On case-insensitive platforms (Windows) convert the path to lower case. On case-sensitive platforms (Unix) leave the path as is. This also turns forward slashes to backslashes on Windows. .split_root() Split this path at the root and return a tuple of two paths: the root and the rest of the path. The root is the same as the first subscript of the ``.components()`` result. Calling ``Path(root, rest)`` or ``os.path.join(root, rest)`` will produce the original path. Examples:: Path("foo/bar.py").components() => [Path(""), Path("foo"), Path("bar.py")] Path("foo/bar.py").split_root() => (Path(""), Path("foo/bar.py")) Path("/foo/bar.py").components() => [Path("/"), Path("foo"), Path("bar.py")] Path("/foo/bar.py").split_root() => (Path("/"), Path("foo/bar.py")) Path("C:\\foo\\bar.py").components() => ["Path("C:\\"), Path("foo"), Path("bar.py")] Path("C:\\foo\\bar.py").split_root() => ("Path("C:\\"), Path("foo\\bar.py")) Path("\\\\UNC_SHARE\\foo\\bar.py").components() => [Path("\\\\UNC_SHARE"), Path("foo"), Path("bar.py")] Path("\\\\UNC_SHARE\\foo\\bar.py").split_root() => (Path("\\\\UNC_SHARE"), Path("foo\\bar.py")) Path("~/bin").expand_user() => Path("/home/guido/bin") Path("~timbot/bin").expand_user() => Path("/home/timbot/bin") Path("$HOME/bin").expand_vars() => Path("/home/guido/bin") Path("~//$BACKUPS").expand() => Path("/home/guido/Backups") Path("dir").child("subdir", "file") => Path("dir/subdir/file") Path("/foo").isabsolute() => True Path("foo").isabsolute() => False Note: a Windows drive-relative path like "C:foo" is considered absolute by ``.components()``, ``.isabsolute()``, and ``.split_root()``, even though Python's ``ntpath.isabs()`` would return false. Path objects only ================= Note on arguments ----------------- All arguments that take paths can also take strings. Current directory ----------------- Path.cwd() Return the actual current directory; e.g., Path("/tmp/my_temp_dir"). This is a class method. .chdir() Make self the current directory. Calculating paths ----------------- .resolve() Return the equivalent path without any symbolic links. This normalizes the path as a side effect. .absolute() Return the absolute equivalent of self. If the path is relative, this prefixes the current directory; i.e., ``FSPath(FSPath.cwd(), p)``. .relative() Return an equivalent path relative to the current directory if possible. This may return a path prefixed with many "../..". If the path is on a different drive, this returns the original path unchanged. .rel_path_to(other) Return a path from self to other. In other words, return a path for 'other' relative to self. Listing directories ------------------- *These methods are experimental and subject to change.* .listdir(pattern=None, filter=ALL, names_only=False) Return the filenames in this directory. 'pattern' may be a glob expression like "\*.py". 'filter' may be a function that takes a ``FSPath`` and returns true if it should be included in the results. The following standard filters are defined in the ``unipath`` module: - ``DIRS``: directories only - ``FILES``: files only - ``LINKS``: symbolic links only - ``FILES_NO_LINKS``: files that aren't symbolic links - ``DIRS_NO_LINKS``: directories that aren't symbolic links - ``DEAD_LINKS``: symbolic links that point to nonexistent files This method normally returns FSPaths prefixed with 'self'. If 'names_only' is true, it returns the raw filenames as strings without a directory prefix (same as ``os.listdir``). If both 'pattern' and 'filter' are specified, only paths that pass both are included. 'filter' must not be specified if 'names_only' is true. Paths are returned in sorted order. .walk(pattern=None, filter=None, top_down=True) Yield ``FSPath`` objects for all files and directories under self, recursing subdirectories. Paths are yielded in sorted order. 'pattern' and 'filter' are the same as for ``.listdir()``. If 'top_down' is true (default), yield directories before yielding the items in them. If false, yield the items first. File attributes and permissions ------------------------------- .atime() Return the path's last access time. .ctime() Return the path's ctime. On Unix this returns the time the path's permissions and ownership were last modified. On Windows it's the path creation time. .exists() Does the path exist? For symbolic links, True if the linked-to file exists. On some platforms this returns False if Python does not have permission to stat the file, even if it exists. .isdir() Is the path a directory? Follows symbolic links. .isfile() Is the path a file? Follows symbolic links. .islink() Is the path a symbolic link? .ismount() Is the path a mount point? Returns true if self's parent is on a different device than self, or if self and its parent are the same directory. .lexists() Same as ``.exists()`` but don't follow a final symbolic link. .lstat() Same as ``.stat()`` but do not follow a final symbolic link. .size() Return the file size in bytes. .stat() Return a stat object to test file size, type, permissions, etc. See ``os.stat()`` for details. .statvfs() Return a ``StatVFS`` object. This method exists only if the platform supports it. See ``os.statvfs()`` for details. Modifying paths --------------- Creating/renaming/removing ++++++++++++++++++++++++++ .chmod(mode) Change the path's permissions. 'mode' is octal; e.g., 0777. .chown(uid, gid) Change the path's ownership to the numeric uid and gid specified. Pass -1 if you don't want one of the IDs changed. .mkdir(parents=False) Create the directory, or succeed silently if it already exists. If 'parents' is true, create any necessary ancestor directories. .remove() Delete the file. Raises OSError if it's a directory. .rename(dst, parents=False) Rename self to 'dst' atomically. See ``os.rename()`` for additional details. If 'parents' is True, create any intermediate destination directories necessary, and delete as many empty leaf source directories as possible. .rmdir(parents=False) Remove the directory, or succeed silently if it's already gone. If 'parents' is true, also remove as many empty ancestor directories as possible. .set_times(mtime=None, atime=None) Set the path's modification and access times. If 'mtime' is None, use the current time. If 'atime' is None or not specified, use the same time as 'mtime'. To set the times based on another file, see ``.copy_stat()``. Symbolic and hard links +++++++++++++++++++++++ .hardlink(src) Create a hard link at 'src' pointing to self. .write_link(target) Create a symbolic link at self pointing to 'target'. The link will contain the exact string value of 'target' without checking whether that path exists or is a even a valid path for the filesystem. .make_relative_link_to(dst) Make a relative symbolic link from self to dst. Same as ``self.write_link(self.rel_path_to(dst))``. (New in Unipath 0.2.0.) .read_link() Return the path that this symbolic link points to. High-level operations --------------------- .copy(dst, times=False, perms=False) Copy the file to a destination. 'times' and 'perms' are same as for ``.copy_stat()``. .copy_stat(dst, times=True, perms=True) Copy the access/modification times and/or the permission bits from this path to another path. .copy_tree(dst, preserve_symlinks=False, times=False, perms=False) Recursively copy a directory tree to 'dst'. 'dst' must not exist; it will be created along with any missing ancestors. If 'symlinks' is true, symbolic links will be recreated with the same path (absolute or relative); otherwise the links will be followed. 'times' and 'perms' are same as ``.copy_stat()``. *This method is not implemented yet.* .move(dst) Recursively move a file or directory to another location. This uses .rename() if possible. .needs_update(other_paths) Return True if self is missing or is older than any other path. 'other_paths' can be a ``(FS)Path``, a string path, or a list/tuple of these. Recurses through subdirectories but compares only files. .read_file(mode="r") Return the file's content as a ``str`` string. This encapsulates the open/read/close. 'mode' is the same as in Python's ``open()`` function. .rmtree(parents=False) Recursively remove this path, no matter whether it's a file or a directory. Succeed silently if the path doesn't exist. If 'parents' is true, also try to remove as many empty ancestor directories as possible. .write_file(content, mode="w") Replace the file's content, creating the file if necessary. 'mode' is the same as in Python's ``open()`` function. 'content' is a ``str`` string. You'll have to encode Unicode strings before calling this. Tools ===== The following functions are in the ``unipath.tools`` module. dict2dir -------- dict2dir(dir, dic, mode="w") => None Create a directory that matches the dict spec. String values are turned into files named after the key. Dict values are turned into subdirectories. 'mode' specifies the mode for files. 'dir' can be an ``[FS]Path`` or a string path. dump_path(path, prefix="", tab=" ", file=None) => None Display an ASCII tree of the path. Files are displayed as "filename (size)". Directories have ":" at the end of the line and indentation below, like Python syntax blocks. Symbolic links are shown as "link -> target". 'prefix' is a string prefixed to every line, normally to controll indentation. 'tab' is the indentation added for each directory level. 'file' specifies an output file object, or ``None`` for ``sys.stdout``. A future version of Unipath will have a command-line program to dump a path. Non-native paths ================ If you want to make Windows-style paths on Unix or vice-versa, you can subclass ``AbstractPath`` and set the ``pathlib`` class attribute to one of Python's OS-specific path modules (``posixpath`` or ``ntpath``) or a third-party equivalent. To convert from one syntax to another, pass the path object to the other constructor. This is not practical with ``Path`` because the OS will reject or misinterpret non-native paths. History ======= 2004-03-07 Released as path.py by Jason Orendorff . That version is a subclass of unicode and combines methods from os.path, os, and shutil, and includes globbing features. Other contributors are listed in the source. - http://www.jorendorff.com/articles/python/path 2005-07 Modified by Reinhold Birkenfeld in preparation for a Python PEP. Convert all filesystem-accessing properties to methods, rename stuff, and use self.__class__ instead of hardwired constructor to aid subclassing. Source was in Python CVS in the "sandbox" section but I can't find it in the current Subversion repository; was it deleted? What's the incantation to bring it back? 2006-01 Modified by Björn Lindqvist for PEP 355. Replace .joinpath() with a multi-argument constructor. - overview: http://www.python.org/dev/peps/pep-0355/ - code: http://wiki.python.org/moin/PathModule 2006 Influenced by Noam Raphael's alternative path module. This subclasses tuple rather than unicode, representing a tuple of directory components a la ``tuple(os.path.splitall("a/b"))``. The discussion covers several design decisions and open issues. - overview: http://wiki.python.org/moin/AlternativePathClass - code: http://wiki.python.org/moin/AlternativePathModule - discussion: http://wiki.python.org/moin/AlternativePathDiscussion 2007-01 Renamed unipath and modified by Mike Orr . Move filesystem operations into a subclass FSPath. Add and rename methods and properties. Influenced by these mailing-list threads: - @@MO coming soon 2008-05 Released version 0.2.0. Renamed ``Path`` to ``AbstractPath``, and ``FSPath`` to ``Path``. Comparision with os/os.path/shutil and path.py ============================================== :: p = any path, f = file, d = directory, l = link fsp, fsf, fsd, fsl = filesystem path (i.e., ``Path`` only) - = not implemented Functions are listed in the same order as the Python Library Reference, version 2.5. (Sorry the table is badly formatted.) :: os/os.path/shutil path.py Unipath Notes ================= ============== ========== ======= os.path.abspath(p) p.abspath() p.absolute() Return absolute path. os.path.basename(p) p.name p.name os.path.commonprefix(p) - - Common prefix. [1]_ os.path.dirname(p) p.parent p.parent All except the last component. os.path.exists(p) p.exists() fsp.exists() Does the path exist? os.path.lexists(p) p.lexists() fsp.lexists() Does the symbolic link exist? os.path.expanduser(p) p.expanduser() p.expand_user() Expand "~" and "~user" prefix. os.path.expandvars(p) p.expandvars() p.expand_vars() Expand "$VAR" environment variables. os.path.getatime(p) p.atime fsp.atime() Last access time. os.path.getmtime(p) p.mtime fsp.mtime() Last modify time. os.path.getctime(p) p.ctime fsp.ctime() Platform-specific "ctime". os.path.getsize(p) p.size fsp.size() File size. os.path.isabs(p) p.isabs() p.isabsolute Is path absolute? os.path.isfile(p) p.isfile() fsp.isfile() Is a file? os.path.isdir(p) p.isdir() fsp.isdir() Is a directory? os.path.islink(p) p.islink() fsp.islink() Is a symbolic link? os.path.ismount(p) p.ismount() fsp.ismount() Is a mount point? os.path.join(p, "Q/R") p.joinpath("Q/R") [FS]Path(p, "Q/R") Join paths. -or- p.child("Q", "R") os.path.normcase(p) p.normcase() p.norm_case() Normalize case. os.path.normpath(p) p.normpath() p.norm() Normalize path. os.path.realpath(p) p.realpath() fsp.real_path() Real path without symbolic links. os.path.samefile(p, q) p.samefile(q) fsp.same_file(q) True if both paths point to the same filesystem item. os.path.sameopenfile(d1, d2) - - [Not a path operation.] os.path.samestat(st1, st2) - - [Not a path operation.] os.path.split(p) p.splitpath() (p.parent, p.name) Split path at basename. os.path.splitdrive(p) p.splitdrive() - [2]_ os.path.splitext(p) p.splitext() - [2]_ os.path.splitunc(p) p.splitunc() - [2]_ os.path.walk(p, func, args) - - [3]_ os.access(p, const) p.access(const) - [4]_ os.chdir(d) - fsd.chdir() Change current directory. os.fchdir(fd) - - [Not a path operation.] os.getcwd() path.getcwd() FSPath.cwd() Get current directory. os.chroot(d) d.chroot() - [5]_ os.chmod(p, 0644) p.chmod(0644) fsp.chmod(0644) Change mode (permission bits). os.chown(p, uid, gid) p.chown(uid, gid) fsp.chown(uid, gid) Change ownership. os.lchown(p, uid, gid) - - [6]_ os.link(src, dst) p.link(dst) fsp.hardlink(dst) Make hard link. os.listdir(d) - fsd.listdir(names_only=True) List directory; return base filenames. os.lstat(p) p.lstat() fsp.lstat() Like stat but don't follow symbolic link. os.mkfifo(p, 0666) - - [Not enough of a path operation.] os.mknod(p, ...) - - [Not enough of a path operation.] os.major(device) - - [Not a path operation.] os.minor(device) - - [Not a path operation.] os.makedev(...) - - [Not a path operation.] os.mkdir(d, 0777) d.mkdir(0777) fsd.mkdir(mode=0777) Create directory. os.makedirs(d, 0777) d.makedirs(0777) fsd.mkdir(True, 0777) Create a directory and necessary parent directories. os.pathconf(p, name) p.pathconf(name) - Return Posix path attribute. (What the hell is this?) os.readlink(l) l.readlink() fsl.read_link() Return the path a symbolic link points to. os.remove(f) f.remove() fsf.remove() Delete file. os.removedirs(d) d.removedirs() fsd.rmdir(True) Remove empty directory and all its empty ancestors. os.rename(src, dst) p.rename(dst) fsp.rename(dst) Rename a file or directory atomically (must be on same device). os.renames(src, dst) p.renames(dst) fsp.rename(dst, True) Combines os.rename, os.makedirs, and os.removedirs. os.rmdir(d) d.rmdir() fsd.rmdir() Delete empty directory. os.stat(p) p.stat() fsp.stat() Return a "stat" object. os.statvfs(p) p.statvfs() fsp.statvfs() Return a "statvfs" object. os.symlink(src, dst) p.symlink(dst) fsp.write_link(link_text) Create a symbolic link. ("write_link" argument order is opposite from Python's!) os.tempnam(...) - - [7]_ os.unlink(f) f.unlink() - Same as .remove(). os.utime(p, times) p.utime(times) fsp.set_times(mtime, atime) Set access/modification times. os.walk(...) - - [3]_ shutil.copyfile(src, dst) f.copyfile(dst) fsf.copy(dst, ...) Copy file. Unipath method is more than copyfile but less than copy2. shutil.copyfileobj(...) - - [Not a path operation.] shutil.copymode(src, dst) p.copymode(dst) fsp.copy_stat(dst, ...) Copy permission bits only. shutil.copystat(src, dst) p.copystat(dst) fsp.copy_stat(dst, ...) Copy stat bits. shutil.copy(src, dst) f.copy(dst) - High-level copy a la Unix "cp". shutil.copy2(src, dst) f.copy2(dst) - High-level copy a la Unix "cp -p". shutil.copytree(...) d.copytree(...) fsp.copy_tree(...) Copy directory tree. (Not implemented in Unipath 0.1.0.) shutil.rmtree(...) d.rmtree(...) fsp.rmtree(...) Recursively delete directory tree. (Unipath has enhancements.) shutil.move(src, dst) p.move(dst) fsp.move(dst) Recursively move a file or directory, using os.rename() if possible. A + B A + B A+B Concatenate paths. os.path.join(A, B) A / B [FS]Path(A, B) Join paths. -or- p.child(B) - p.expand() p.expand() Combines expanduser, expandvars, normpath. os.path.dirname(p) p.parent p.parent Path without final component. os.path.basename(p) p.name p.name Final component only. [8]_ p.namebase p.stem Final component without extension. [9]_ p.ext p.ext Extension only. os.path.splitdrive(p)[0] p.drive - [2]_ - p.stripext() - Strip final extension. - p.uncshare - [2]_ - p.splitall() p.components() List of path components. (Unipath has special first element.) - p.relpath() fsp.relative() Relative path to current directory. - p.relpathto(dst) fsp.rel_path_to(dst) Relative path to 'dst'. - d.listdir() fsd.listdir() List directory, return paths. - d.files() fsd.listdir(filter=FILES) List files in directory, return paths. - d.dirs() fsd.listdir(filter=DIRS) List subdirectories, return paths. - d.walk(...) fsd.walk(...) Recursively yield files and directories. - d.walkfiles(...) fsd.walk(filter=FILES) Recursively yield files. - d.walkdirs(...) fsd.walk(filter=DIRS) Recursively yield directories. - p.fnmatch(pattern) - True if self.name matches glob pattern. - p.glob(pattern) - Advanced globbing. - f.open(mode) - Return open file object. - f.bytes() fsf.read_file("rb") Return file contents in binary mode. - f.write_bytes() fsf.write_file(content, "wb") Replace file contents in binary mode. - f.text(...) fsf.read_file() Return file content. (Encoding args not implemented yet.) - f.write_text(...) fsf.write_file(content) Replace file content. (Not all Orendorff args supported.) - f.lines(...) - Return list of lines in file. - f.write_lines(...) - Write list of lines to file. - f.read_md5() - Calculate MD5 hash of file. - p.owner - Advanded "get owner" operation. - p.readlinkabs() - Return the path this symlink points to, converting to absolute path. - p.startfile() - What the hell is this? - - p.split_root() Unified "split root" method. - - p.ancestor(N) Same as specifying .parent N times. - - p.child(...) "Safe" way to join paths. - - fsp.needs_update(...) True if self is missing or older than any of the other paths. .. [1] The Python method is too dumb; it can end a prefix in the middle of a .. [2] Closest equivalent is ``p.split_root()`` for approximate equivalent. .. [3] More convenient alternatives exist. .. [4] Inconvenient constants; not used enough to port. .. [5] Chroot is more of an OS operation than a path operation. Plus it's dangerous. .. [6] Ownership of symbolic link doesn't matter because the OS never consults its permission bits. .. [7]_ ``os.tempnam`` is insecure; use ``os.tmpfile`` or ``tempfile`` module instead. .. [8]_ ``os.path.splitext(os.path.split(p))[0]`` .. [9]_ ``os.path.splitext(os.path.split(p))[1]`` .. [10]_ Closest equivalent is ``p.split_root()[0]``. Design decisions / open issues ============================== (Sorry this is so badly organized.) The original impetus for Unipath was to get object-oriented paths into the Python standard library. All the previous path classes were rejected as too large and monolithic, especially for mixing pathname manipulations and filesystem methods in the same class. Upon reflection, it's mainly the pathname operations that need to be OO-ified because they are often nested in expressions. There's a small difference between ``p.mkdir()`` and ``os.mkdir(p)``, but there's a huge difference between ``os.path.join(os.path.dirname(os.path.dirname("/A/B/C"))), "app2/lib")`` and ``Path("/A/B/C").parent.parent.child("app2", "lib")``: the former is flat-out unreadable. So I have kept ``Path`` to a conservative API that hopefully most Pythoneers can agree on. I allowed myself more freedom with ``FSPath`` because it's unclear that a class with filesystem methods would ever be accepted into the stdlib anyway, and I needed an API I'd want to use in my own programs. (``Path`` was renamed to ``AbstractPath`` in Unipath 0.2.0, and ``FSPath`` to ``Path``. This section uses the older vocabulary.) Another important point is that properties may not access the filesystem. Only methods may access the filesystem. So ``p.parent`` is a property, but ``p.mtime()`` is a method. This required turning some of Orendorff's properties into methods. The actual ``FSPath`` class ended up closer to Orendorff's original than I had intended, because several of the planned innovations (from python-3000 suggestions, Raphael's alternative path class, and my own mind) turned to be not necessarily superior in actual programs, whereas Orendorff's methods have proven themselves reliable in production systems for three years now, so I deferred to them when in doubt. The biggest such move was making ``FSPath`` a subclass of ``Path``. Originally I had tried to make them unrelated classes (``FSPath`` containing a ``Path``), but this became unworkable in the implementation due to the constant need to call both types of methods. (Say you have an FSPath directory and you need to join a filename to it and then delete the file; do you really want to convert from FSPath to Path and back again? Do you *really* want to write "FSPath(Path(my_fspath.path, 'foo'))"?) So one class is better than two, even if the BDFL disapproves. I opted for the best of both worlds via inheritance, so those who want one class can pretend it is, and those who want two classes can get a warm fuzzy feeling that they're defined separately. (They can even ignore ``FSPath`` and use ``Path`` with ``os.*`` functions if they prefer.) If ``Path`` is someday accepted into the standard libary, ``FSPath`` will become a subclass of that. And others can subclass ``FSPath`` or write an alternative if they don't like my API. I also intended to put all non-trivial code into generic functions that third-party path libraries could call. But that also became unworkable due to the tight integration that naturally occurs between the methods, one calling another. What's really needed now is for ``FSPath`` to get into the real world so we can see which generic code actually is valuable, and then those can be factored out later. ``.stem`` is called stem because "namebase" can be confused with ``os.path.basename()``, "name_without_ext" is too wordy, and "name_no_ext" is looks like bad English. All method names have underscores between words except those starting with "is", "mk", "rm", and "stat". The "is" methods are so highly used that deviating from the ``os.path``/Orendorff spelling would trip up a lot of programmers, including me. "mk" and "rm" I just like. (Be glad I didn't rename ``.copy_tree`` to "cptree" to match ``.rmtree``.) (or ".drive" and ".unc" properties) are not needed. They may be added if they prove necessary, but then how do you get "everything except the drive" or "everything except the UNC prefix". I also had to move the slash following the UNC prefix to the prefix itself, to maintain the rule that everything after the first component is a relative path. I tried making a smart stat object so that one could do "p.stat().size" and "p.stat().isdir". This was one of the proposals for Raphael's class, to get rid of a bunch of top-level methods and obviate the need for a set of "l" methods covering the "stat" and "lstat" operations. I also made a phony stat object if the path didn't exist, to hang the ".exists" attribute off. But I was so used to typing ``p.isdir()`` etc from Orendorff that I couldn't adjust. And Python has only one "l" function anyway, ``os.path.lexists()``. *And* I didn't want to write the stat object in C, meaning every stat would incur Python overhead to convert the result attributes. So in the end I decided to keep the methods shadowing the ``os.path`` convenience functions, remove the "get" prefix from the "get" methods ("getmtime"), and let ``.stat`` and ``.statvfs`` return the Python default object. I'm still tempted to make ``.stat()`` and ``.statvfs`` return ``None`` if the path doesn't exist (rather than raising ``OSError``), but I'm not sure that's necessarily *better* so I held off on that. Presumably one wouldn't use ``.stat()`` that much anyway since the other methods are more convenient. ``.components()`` comes from Raphael's class, the concept of treating paths as a list of components, with the first component being the filesystem root (for an absolute path). This required unifying Posix and Windows roots into a common definition. ``.split_root()`` handles drive paths and UNC paths, so "splitdrive" and "splitunc" (or ".drive" and ".unc" properties) were deemed unnecessary. They may be added later if needed. One problem with ".drive" and ".unc" properties is how to specify "everything except the drive" and "everything except the UNC prefix", which are needed to recreate the path or derive a similar path. The slash after the UNC prefix was also moved to the prefix, to maintain the rule that all components after the first make a relative path. "Components" turned out to be a useful way to convert paths from one platform to another, which was one of Talin's requests. However, what Talin really wanted was to put Posix paths in a config file and have them translate to the native platform. Since ``.norm()`` and ``.norm_case()`` already do this on Windows, it's questionable how much cross-platform support is really necessary. Especially since ``macpath`` is obsolete now that Mac OS X uses Posix, and Mac OS 9 is about to be dropped from Python. So the multi-platform code is probational. Joining paths is done via the constructor, which takes multiple positional arguments. This was deemed as better than Orendorff's ".joinpath" method for reasons I'm not sure of. ``.child()`` was requested by Glyph, to create safe subpaths that can never reach outside their parent directory even if based on untrusted user strings. It's also sneaky way to do "joinpath" when you're really prefer to use a method rather than the costructor, as long as each component has to be passed as a separate argument. Orendorff has ".listdir", ".dirs", and ".files" methods (non-recursive), and ".walk", ".walkdirs", and "walkfiles" (recursive). Raphael has one ".glob" method to rule them all. I went back and forth on this several times and finally settled on ``.listdir`` (non-recursive) and ``.walk`` (recursive), with a 'filter' argument to return only files or directories. Neither Orendorff nor Raphael nor ``os.walk`` handle symlinks adequately in my opinion: sometimes you want to exclude symlinks and then list them separately. ``.listdir`` has a 'names_only' option to make it return just the filenames like ``os.listdir``, because sometimes that's what you need, and there's no reason to create paths you're just going to unpack again anyway. ``.listdir`` and ``.walk`` are separate methods because implementing them as one is complicated -- they have so many contingencies. ``.listdir()`` and ``.listdir(names_only=True)`` are the same method because I couldn't come up with a better name for the former. I dropped the name "glob" because it's meaningless to non-Unix users. ``.absolute``, ``.relative``, and ``.resolve`` are hopefully better named than Orendorff's "abspath", "relpath", and "realpath", which were taken directly from ``os.path``. ``.hardlink`` is so-named because it's less used than ``.symlink`` nowadays, and a method named ".link" is easy to misinterpret. I wanted a symbolic syntax for ``.chmod`` ("u=rwx,g+w") and a companion function to parse a numeric mode, and user names/group names for ``.chown``, but those were deferred to get the basic classes out the door. The methods take the same arguments as their ``os`` counterparts. Unipath-0.2.1/README.html0000644000175000017500000020130611013773726013134 0ustar msomso UNIPATH

UNIPATH

An object-oriented approach to file/directory operations

Version: 0.2.0 (2008-05-17)
Home page:http://sluggo.scrapping.cc/python/unipath/
Author: Mike Orr <sluggoster@gmail.com>
License:Python (http://www.python.org/psf/license)
Based on:See HISTORY section below.

Introduction

Unipath is an object-oriented front end to the file/directory functions scattered throughout several Python library modules. It's based on Jason Orendorff's path.py but does not adhere as strictly to the underlying functions' syntax, in order to provide more user convenience and higher-level functionality. It comes with a test suite.

Important

Changes for Unipath 0.1.0 users

Path has been renamed to AbstractPath, and FSPath to Path. FSPath remains as an alias for backward compatibility. Path.symlink() is gone; use Path.write_link() instead. (Note that the argument order is the opposite.) See CHANGES.txt for the complete list of changes.

The Path class encapsulates the file/directory operations in Python's os, os.path, and shutil modules.

Its superclass AbstractPath class encapsulates those operations which aren't dependent on the filesystem. This is mainly an academic distinction to keep the code clean. Since Path can do everything AbstractPath does, most users just use Path.

The API has been streamlined to focus on what the application developer wants to do rather than on the lowest-level operations; e.g., .mkdir() succeeds silently if the directory already exists, and .rmtree() doesn't barf if the target is a file or doesn't exist. This allows the developer to write simple calls that "just work" rather than entire if-stanzas to handle low-level details s/he doesn't care about. This makes applications more self-documenting and less cluttered.

Convenience methods:

  • .read_file and .write_file encapsulate the open/read/close pattern.
  • .needs_update(others) tells whether the path needs updating; i.e., if it doesn't exist or is older than any of the other paths.
  • .ancestor(N) returns the Nth parent directory, useful for joining paths.
  • .child(\*components) is a "safe" version of join.
  • .split_root() handles slash/drive/UNC absolute paths in a uniform way.
  • Optional high-level functions in the unipath.tools module.
  • For Python >= 2.4
  • Path objects are immutable so can be used as dictionary keys.

Sample usage for pathname manipulation:

>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'
>>> p.stem
Path('gopherlib')
>>> q = Path(p.parent, p.stem + p.ext)
>>> q
Path('/usr/lib/python2.5/gopherlib.py')
>>> q == p
True

Sample usage for filesystem access:

>>> import tempfile
>>> from unipath import Path
>>> d = Path(tempfile.mkdtemp())
>>> d.isdir()
True
>>> p = Path(d, "sample.txt")
>>> p.exists()
False
>>> p.write_file("The king is a fink!")
>>> p.exists()
True
>>> print p.read_file()
The king is a fink!
>>> d.rmtree()
>>> p.exists()
False

The name "Unipath" is short for "universal path", as it grew out of a discussion on python-dev about the ideal path API for Python.

Unipath's API is mostly stable but there's no guarantee it won't change in future versions.

Installation and testing

If you have EasyInstall, run "easy_install unipath". Otherwise unpack the source and run "python setup.py install" in the top-level directory. You can also copy the "unipath" directory to somewhere on your Python path.

To test the library you'll need the Nose package. cd to the top-level directory and run "python unipath/test.py".

Path and AbstractPath objects

Constructor

Path (and AbstractPath) objects can be created from a string path, or from several string arguments which are joined together a la os.path.join. Each argument can be a string, an (Abstract)Path instance, an int or long, or a list/tuple of strings to be joined:

p = Path("foo/bar.py")       # A relative path
p = Path("foo", "bar.py")    # Same as previous
p = Path(["foo", "bar.py"])  # Same as previous
p = Path("/foo", "bar", "baz.py")       # An absolute path: /foo/bar/baz.py
p = Path("/foo", Path("bar/baz.py"))    # Same as previous
p = Path("/foo", ["", "bar", "baz.py"]) # Embedded Path.components() result
p = Path("record", 123)      # Same as Path("record/123")

p = Path("")     # An empty path
p = Path()       # Same as Path(os.curdir)

To get the actual current directory, use Path.cwd(). (This doesn't work with AbstractPath, of course.

Adding two paths results in a concatenated path. The other string methods return strings, so you'll have to wrap them in Path to make them paths again. A future version will probably override these methods to return paths. Multiplying a path returns a string, as if you'd ever want to do that.

Normalization

The new path is normalized to clean up redundant ".." and "." in the middle, double slashes, wrong-direction slashes, etc. On case-insensitive filesystems it also converts uppercase to lowercase. This is all done via os.path.normpath(). Here are some examples of normalizations:

a//b  => a/b
a/../b => b
a/./b => a/b

a/b => a\\b            # On NT.
a\\b.JPG => a\\b.jpg   # On NT.

If the actual filesystem path contains symbolic links, normalizing ".." goes to the parent of the symbolic link rather than to the parent of the linked-to file. For this reason, and because there may be other cases where normalizing produces the wrong path, you can disable automatic normalization by setting the .auto_norm class attribute to false. I'm not sure whether Unipath should normalize by default, so if you care one way or the other you should explicitly set it at the beginning of your application. You can override the auto_norm setting by passing "norm=True" or "norm=False" as a keyword argument to the constructor. You can also call .norm() anytime to manually normalize the path.

Properties

Path objects have the following properties:

.parent
The path without the final component.
.name
The final component only.
.ext
The last part of the final component beginning with a dot (e.g., ".gz"), or "" if there is no dot. This is also known as the extension.
.stem
The final component without the extension.

Examples are given in the first sample usage above.

Methods

Path objects have the following methods:

.ancestor(N)
Same as specifying .parent N times.
.child(*components)
Join paths in a safe manner. The child components may not contain a path separator or be curdir or pardir ("." or ".." on Posix). This is to prevent untrusted arguments from creating a path above the original path's directory.
.components()
Return a list of directory components as strings. The first component will be the root ("/" on Posix, a Windows drive root, or a UNC share) if the path is absolute, or "" if it's relative. Calling Path(components), Path(*components), or os.path.join(*components) will recreate the original path.
.expand()
Same as p.expand_user().expand_vars().norm(). Usually this is all you need to fix up a path read from a config file.
.expand_user()
Interpolate "~" and "~user" if the platform allows, and return a new path.
.expand_vars()
Interpolate environment variables like "$BACKUPS" if the platform allows, and return a new path.
.isabsolute()
Is the path absolute?
.norm()
See Normalization above. Same as os.path.normpath.
.norm_case()
On case-insensitive platforms (Windows) convert the path to lower case. On case-sensitive platforms (Unix) leave the path as is. This also turns forward slashes to backslashes on Windows.
.split_root()
Split this path at the root and return a tuple of two paths: the root and the rest of the path. The root is the same as the first subscript of the .components() result. Calling Path(root, rest) or os.path.join(root, rest) will produce the original path.

Examples:

Path("foo/bar.py").components() =>
    [Path(""), Path("foo"), Path("bar.py")]
Path("foo/bar.py").split_root() =>
    (Path(""), Path("foo/bar.py"))

Path("/foo/bar.py").components() =>
    [Path("/"), Path("foo"), Path("bar.py")]
Path("/foo/bar.py").split_root() =>
    (Path("/"), Path("foo/bar.py"))

Path("C:\\foo\\bar.py").components() =>
    ["Path("C:\\"), Path("foo"), Path("bar.py")]
Path("C:\\foo\\bar.py").split_root() =>
    ("Path("C:\\"), Path("foo\\bar.py"))

Path("\\\\UNC_SHARE\\foo\\bar.py").components() =>
    [Path("\\\\UNC_SHARE"), Path("foo"), Path("bar.py")]
Path("\\\\UNC_SHARE\\foo\\bar.py").split_root() =>
    (Path("\\\\UNC_SHARE"), Path("foo\\bar.py"))

Path("~/bin").expand_user() => Path("/home/guido/bin")
Path("~timbot/bin").expand_user() => Path("/home/timbot/bin")
Path("$HOME/bin").expand_vars() => Path("/home/guido/bin")
Path("~//$BACKUPS").expand() => Path("/home/guido/Backups")

Path("dir").child("subdir", "file") => Path("dir/subdir/file")

Path("/foo").isabsolute() => True
Path("foo").isabsolute() => False

Note: a Windows drive-relative path like "C:foo" is considered absolute by .components(), .isabsolute(), and .split_root(), even though Python's ntpath.isabs() would return false.

Path objects only

Note on arguments

All arguments that take paths can also take strings.

Current directory

Path.cwd()
Return the actual current directory; e.g., Path("/tmp/my_temp_dir"). This is a class method.
.chdir()
Make self the current directory.

Calculating paths

.resolve()
Return the equivalent path without any symbolic links. This normalizes the path as a side effect.
.absolute()
Return the absolute equivalent of self. If the path is relative, this prefixes the current directory; i.e., FSPath(FSPath.cwd(), p).
.relative()
Return an equivalent path relative to the current directory if possible. This may return a path prefixed with many "../..". If the path is on a different drive, this returns the original path unchanged.
.rel_path_to(other)
Return a path from self to other. In other words, return a path for 'other' relative to self.

Listing directories

These methods are experimental and subject to change.

.listdir(pattern=None, filter=ALL, names_only=False)

Return the filenames in this directory.

'pattern' may be a glob expression like "*.py".

'filter' may be a function that takes a FSPath and returns true if it should be included in the results. The following standard filters are defined in the unipath module:

  • DIRS: directories only
  • FILES: files only
  • LINKS: symbolic links only
  • FILES_NO_LINKS: files that aren't symbolic links
  • DIRS_NO_LINKS: directories that aren't symbolic links
  • DEAD_LINKS: symbolic links that point to nonexistent files

This method normally returns FSPaths prefixed with 'self'. If 'names_only' is true, it returns the raw filenames as strings without a directory prefix (same as os.listdir).

If both 'pattern' and 'filter' are specified, only paths that pass both are included. 'filter' must not be specified if 'names_only' is true.

Paths are returned in sorted order.

.walk(pattern=None, filter=None, top_down=True)

Yield FSPath objects for all files and directories under self, recursing subdirectories. Paths are yielded in sorted order.

'pattern' and 'filter' are the same as for .listdir().

If 'top_down' is true (default), yield directories before yielding the items in them. If false, yield the items first.

File attributes and permissions

.atime()
Return the path's last access time.
.ctime()
Return the path's ctime. On Unix this returns the time the path's permissions and ownership were last modified. On Windows it's the path creation time.
.exists()
Does the path exist? For symbolic links, True if the linked-to file exists. On some platforms this returns False if Python does not have permission to stat the file, even if it exists.
.isdir()
Is the path a directory? Follows symbolic links.
.isfile()
Is the path a file? Follows symbolic links.
.islink()
Is the path a symbolic link?
.ismount()
Is the path a mount point? Returns true if self's parent is on a different device than self, or if self and its parent are the same directory.
.lexists()
Same as .exists() but don't follow a final symbolic link.
.lstat()
Same as .stat() but do not follow a final symbolic link.
.size()
Return the file size in bytes.
.stat()
Return a stat object to test file size, type, permissions, etc. See os.stat() for details.
.statvfs()
Return a StatVFS object. This method exists only if the platform supports it. See os.statvfs() for details.

Modifying paths

Creating/renaming/removing

.chmod(mode)
Change the path's permissions. 'mode' is octal; e.g., 0777.
.chown(uid, gid)
Change the path's ownership to the numeric uid and gid specified. Pass -1 if you don't want one of the IDs changed.
.mkdir(parents=False)
Create the directory, or succeed silently if it already exists. If 'parents' is true, create any necessary ancestor directories.
.remove()
Delete the file. Raises OSError if it's a directory.
.rename(dst, parents=False)
Rename self to 'dst' atomically. See os.rename() for additional details. If 'parents' is True, create any intermediate destination directories necessary, and delete as many empty leaf source directories as possible.
.rmdir(parents=False)
Remove the directory, or succeed silently if it's already gone. If 'parents' is true, also remove as many empty ancestor directories as possible.
.set_times(mtime=None, atime=None)
Set the path's modification and access times. If 'mtime' is None, use the current time. If 'atime' is None or not specified, use the same time as 'mtime'. To set the times based on another file, see .copy_stat().

Symbolic and hard links

.hardlink(src)
Create a hard link at 'src' pointing to self.
.write_link(target)
Create a symbolic link at self pointing to 'target'. The link will contain the exact string value of 'target' without checking whether that path exists or is a even a valid path for the filesystem.
.make_relative_link_to(dst)
Make a relative symbolic link from self to dst. Same as self.write_link(self.rel_path_to(dst)). (New in Unipath 0.2.0.)
.read_link()
Return the path that this symbolic link points to.

High-level operations

.copy(dst, times=False, perms=False)
Copy the file to a destination. 'times' and 'perms' are same as for .copy_stat().
.copy_stat(dst, times=True, perms=True)
Copy the access/modification times and/or the permission bits from this path to another path.
.copy_tree(dst, preserve_symlinks=False, times=False, perms=False)
Recursively copy a directory tree to 'dst'. 'dst' must not exist; it will be created along with any missing ancestors. If 'symlinks' is true, symbolic links will be recreated with the same path (absolute or relative); otherwise the links will be followed. 'times' and 'perms' are same as .copy_stat(). This method is not implemented yet.
.move(dst)
Recursively move a file or directory to another location. This uses .rename() if possible.
.needs_update(other_paths)
Return True if self is missing or is older than any other path. 'other_paths' can be a (FS)Path, a string path, or a list/tuple of these. Recurses through subdirectories but compares only files.
.read_file(mode="r")
Return the file's content as a str string. This encapsulates the open/read/close. 'mode' is the same as in Python's open() function.
.rmtree(parents=False)
Recursively remove this path, no matter whether it's a file or a directory. Succeed silently if the path doesn't exist. If 'parents' is true, also try to remove as many empty ancestor directories as possible.
.write_file(content, mode="w")
Replace the file's content, creating the file if necessary. 'mode' is the same as in Python's open() function. 'content' is a str string. You'll have to encode Unicode strings before calling this.

Tools

The following functions are in the unipath.tools module.

dict2dir

dict2dir(dir, dic, mode="w") => None

Create a directory that matches the dict spec. String values are turned into files named after the key. Dict values are turned into subdirectories. 'mode' specifies the mode for files. 'dir' can be an [FS]Path or a string path.

dump_path(path, prefix="", tab=" ", file=None) => None

Display an ASCII tree of the path. Files are displayed as "filename (size)". Directories have ":" at the end of the line and indentation below, like Python syntax blocks. Symbolic links are shown as "link -> target". 'prefix' is a string prefixed to every line, normally to controll indentation. 'tab' is the indentation added for each directory level. 'file' specifies an output file object, or None for sys.stdout.

A future version of Unipath will have a command-line program to dump a path.

Non-native paths

If you want to make Windows-style paths on Unix or vice-versa, you can subclass AbstractPath and set the pathlib class attribute to one of Python's OS-specific path modules (posixpath or ntpath) or a third-party equivalent. To convert from one syntax to another, pass the path object to the other constructor.

This is not practical with Path because the OS will reject or misinterpret non-native paths.

History

2004-03-07

Released as path.py by Jason Orendorff <jason@jorendorff.com>. That version is a subclass of unicode and combines methods from os.path, os, and shutil, and includes globbing features. Other contributors are listed in the source.

2005-07
Modified by Reinhold Birkenfeld in preparation for a Python PEP. Convert all filesystem-accessing properties to methods, rename stuff, and use self.__class__ instead of hardwired constructor to aid subclassing. Source was in Python CVS in the "sandbox" section but I can't find it in the current Subversion repository; was it deleted? What's the incantation to bring it back?
2006-01

Modified by Björn Lindqvist <bjourne@gmail.com> for PEP 355. Replace .joinpath() with a multi-argument constructor.

2006

Influenced by Noam Raphael's alternative path module. This subclasses tuple rather than unicode, representing a tuple of directory components a la tuple(os.path.splitall("a/b")). The discussion covers several design decisions and open issues.

2007-01

Renamed unipath and modified by Mike Orr <sluggoster@gmail.com>. Move filesystem operations into a subclass FSPath. Add and rename methods and properties. Influenced by these mailing-list threads:

  • @@MO coming soon
2008-05
Released version 0.2.0. Renamed Path to AbstractPath, and FSPath to Path.

Comparision with os/os.path/shutil and path.py

p = any path, f =  file, d = directory, l = link
fsp, fsf, fsd, fsl = filesystem path (i.e., ``Path`` only)
- = not implemented

Functions are listed in the same order as the Python Library Reference, version 2.5. (Sorry the table is badly formatted.)

os/os.path/shutil      path.py        Unipath           Notes
=================      ============== ==========        =======
os.path.abspath(p)     p.abspath()    p.absolute()     Return absolute path.
os.path.basename(p)    p.name         p.name
os.path.commonprefix(p)  -            -                Common prefix. [1]_
os.path.dirname(p)     p.parent       p.parent         All except the last component.
os.path.exists(p)      p.exists()     fsp.exists()     Does the path exist?
os.path.lexists(p)     p.lexists()    fsp.lexists()    Does the symbolic link exist?
os.path.expanduser(p)  p.expanduser() p.expand_user()  Expand "~" and "~user" prefix.
os.path.expandvars(p)  p.expandvars() p.expand_vars()  Expand "$VAR" environment variables.
os.path.getatime(p)    p.atime        fsp.atime()      Last access time.
os.path.getmtime(p)    p.mtime        fsp.mtime()      Last modify time.
os.path.getctime(p)    p.ctime        fsp.ctime()      Platform-specific "ctime".
os.path.getsize(p)     p.size         fsp.size()       File size.
os.path.isabs(p)       p.isabs()      p.isabsolute     Is path absolute?
os.path.isfile(p)      p.isfile()     fsp.isfile()     Is a file?
os.path.isdir(p)       p.isdir()      fsp.isdir()      Is a directory?
os.path.islink(p)      p.islink()     fsp.islink()     Is a symbolic link?
os.path.ismount(p)     p.ismount()    fsp.ismount()    Is a mount point?
os.path.join(p, "Q/R") p.joinpath("Q/R")  [FS]Path(p, "Q/R")  Join paths.
                                          -or-
                                          p.child("Q", "R")
os.path.normcase(p)    p.normcase()    p.norm_case()   Normalize case.
os.path.normpath(p)    p.normpath()    p.norm()        Normalize path.
os.path.realpath(p)    p.realpath()    fsp.real_path() Real path without symbolic links.
os.path.samefile(p, q) p.samefile(q)   fsp.same_file(q)  True if both paths point to the same filesystem item.
os.path.sameopenfile(d1, d2)  -          -               [Not a path operation.]
os.path.samestat(st1, st2)    -          -               [Not a path operation.]
os.path.split(p)       p.splitpath()   (p.parent, p.name) Split path at basename.
os.path.splitdrive(p)  p.splitdrive()   -                 [2]_
os.path.splitext(p)    p.splitext()     -                 [2]_
os.path.splitunc(p)    p.splitunc()     -                 [2]_
os.path.walk(p, func, args)  -          -                 [3]_

os.access(p, const)    p.access(const)  -                 [4]_
os.chdir(d)            -                fsd.chdir()       Change current directory.
os.fchdir(fd)          -                -                 [Not a path operation.]
os.getcwd()           path.getcwd()     FSPath.cwd()      Get current directory.
os.chroot(d)          d.chroot()        -                 [5]_
os.chmod(p, 0644)     p.chmod(0644)     fsp.chmod(0644)     Change mode (permission bits).
os.chown(p, uid, gid) p.chown(uid, gid) fsp.chown(uid, gid) Change ownership.
os.lchown(p, uid, gid) -                -                 [6]_
os.link(src, dst)     p.link(dst)       fsp.hardlink(dst)   Make hard link.
os.listdir(d)         -                 fsd.listdir(names_only=True)  List directory; return base filenames.
os.lstat(p)           p.lstat()         fsp.lstat()         Like stat but don't follow symbolic link.
os.mkfifo(p, 0666)    -                 -                 [Not enough of a path operation.]
os.mknod(p, ...)      -                 -                 [Not enough of a path operation.]
os.major(device)      -                 -                 [Not a path operation.]
os.minor(device)      -                 -                 [Not a path operation.]
os.makedev(...)       -                 -                 [Not a path operation.]
os.mkdir(d, 0777)     d.mkdir(0777)     fsd.mkdir(mode=0777)     Create directory.
os.makedirs(d, 0777)  d.makedirs(0777)  fsd.mkdir(True, 0777)    Create a directory and necessary parent directories.
os.pathconf(p, name)  p.pathconf(name)  -                  Return Posix path attribute.  (What the hell is this?)
os.readlink(l)        l.readlink()      fsl.read_link()      Return the path a symbolic link points to.
os.remove(f)          f.remove()        fsf.remove()       Delete file.
os.removedirs(d)      d.removedirs()    fsd.rmdir(True)    Remove empty directory and all its empty ancestors.
os.rename(src, dst)   p.rename(dst)     fsp.rename(dst)      Rename a file or directory atomically (must be on same device).
os.renames(src, dst)  p.renames(dst)    fsp.rename(dst, True) Combines os.rename, os.makedirs, and os.removedirs.
os.rmdir(d)           d.rmdir()         fsd.rmdir()        Delete empty directory.
os.stat(p)            p.stat()          fsp.stat()         Return a "stat" object.
os.statvfs(p)         p.statvfs()       fsp.statvfs()      Return a "statvfs" object.
os.symlink(src, dst)  p.symlink(dst)    fsp.write_link(link_text)   Create a symbolic link.
                                        ("write_link" argument order is opposite from Python's!)
os.tempnam(...)       -                 -                  [7]_
os.unlink(f)          f.unlink()        -                  Same as .remove().
os.utime(p, times)    p.utime(times)    fsp.set_times(mtime, atime)  Set access/modification times.
os.walk(...)          -                 -                  [3]_

shutil.copyfile(src, dst)  f.copyfile(dst) fsf.copy(dst, ...)  Copy file.  Unipath method is more than copyfile but less than copy2.
shutil.copyfileobj(...)   -             -                  [Not a path operation.]
shutil.copymode(src, dst) p.copymode(dst)  fsp.copy_stat(dst, ...)  Copy permission bits only.
shutil.copystat(src, dst) p.copystat(dst)  fsp.copy_stat(dst, ...)  Copy stat bits.
shutil.copy(src, dst)  f.copy(dst)      -                  High-level copy a la Unix "cp".
shutil.copy2(src, dst) f.copy2(dst)     -                  High-level copy a la Unix "cp -p".
shutil.copytree(...)  d.copytree(...)   fsp.copy_tree(...)   Copy directory tree.  (Not implemented in Unipath 0.1.0.)
shutil.rmtree(...)    d.rmtree(...)     fsp.rmtree(...)    Recursively delete directory tree.  (Unipath has enhancements.)
shutil.move(src, dst) p.move(dst)       fsp.move(dst)      Recursively move a file or directory, using os.rename() if possible.

A + B                 A + B             A+B                Concatenate paths.
os.path.join(A, B)    A / B             [FS]Path(A, B)     Join paths.
                                        -or-
                                        p.child(B)
-                     p.expand()        p.expand()         Combines expanduser, expandvars, normpath.
os.path.dirname(p)    p.parent          p.parent           Path without final component.
os.path.basename(p)   p.name            p.name             Final component only.
[8]_                  p.namebase        p.stem             Final component without extension.
[9]_                  p.ext             p.ext              Extension only.
os.path.splitdrive(p)[0] p.drive        -                  [2]_
-                     p.stripext()      -                  Strip final extension.
-                     p.uncshare        -                  [2]_
-                     p.splitall()      p.components()     List of path components.  (Unipath has special first element.)
-                     p.relpath()       fsp.relative()       Relative path to current directory.
-                     p.relpathto(dst)  fsp.rel_path_to(dst) Relative path to 'dst'.
-                     d.listdir()       fsd.listdir()        List directory, return paths.
-                     d.files()         fsd.listdir(filter=FILES)  List files in directory, return paths.
-                     d.dirs()          fsd.listdir(filter=DIRS)   List subdirectories, return paths.
-                     d.walk(...)       fsd.walk(...)        Recursively yield files and directories.
-                     d.walkfiles(...)  fsd.walk(filter=FILES)  Recursively yield files.
-                     d.walkdirs(...)   fsd.walk(filter=DIRS)  Recursively yield directories.
-                     p.fnmatch(pattern)  -                 True if self.name matches glob pattern.
-                     p.glob(pattern)   -                   Advanced globbing.
-                     f.open(mode)      -                   Return open file object.
-                     f.bytes()         fsf.read_file("rb")   Return file contents in binary mode.
-                     f.write_bytes()   fsf.write_file(content, "wb")  Replace file contents in binary mode.
-                     f.text(...)       fsf.read_file()       Return file content.  (Encoding args not implemented yet.)
-                     f.write_text(...) fsf.write_file(content)  Replace file content.  (Not all Orendorff args supported.)
-                     f.lines(...)      -                   Return list of lines in file.
-                     f.write_lines(...)  -                 Write list of lines to file.
-                     f.read_md5()      -                   Calculate MD5 hash of file.
-                     p.owner           -                   Advanded "get owner" operation.
-                     p.readlinkabs()   -                   Return the path this symlink points to, converting to absolute path.
-                     p.startfile()     -                   What the hell is this?

-                     -                 p.split_root()      Unified "split root" method.
-                     -                 p.ancestor(N)       Same as specifying .parent N times.
-                     -                 p.child(...)        "Safe" way to join paths.
-                     -                 fsp.needs_update(...) True if self is missing or older than any of the other paths.
[1]The Python method is too dumb; it can end a prefix in the middle of a
[2]Closest equivalent is p.split_root() for approximate equivalent.
[3]More convenient alternatives exist.
[4]Inconvenient constants; not used enough to port.
[5]Chroot is more of an OS operation than a path operation. Plus it's dangerous.
[6]Ownership of symbolic link doesn't matter because the OS never consults its permission bits.

Design decisions / open issues

(Sorry this is so badly organized.)

The original impetus for Unipath was to get object-oriented paths into the Python standard library. All the previous path classes were rejected as too large and monolithic, especially for mixing pathname manipulations and filesystem methods in the same class. Upon reflection, it's mainly the pathname operations that need to be OO-ified because they are often nested in expressions. There's a small difference between p.mkdir() and os.mkdir(p), but there's a huge difference between os.path.join(os.path.dirname(os.path.dirname("/A/B/C"))), "app2/lib") and Path("/A/B/C").parent.parent.child("app2", "lib"): the former is flat-out unreadable. So I have kept Path to a conservative API that hopefully most Pythoneers can agree on. I allowed myself more freedom with FSPath because it's unclear that a class with filesystem methods would ever be accepted into the stdlib anyway, and I needed an API I'd want to use in my own programs. (Path was renamed to AbstractPath in Unipath 0.2.0, and FSPath to Path. This section uses the older vocabulary.)

Another important point is that properties may not access the filesystem. Only methods may access the filesystem. So p.parent is a property, but p.mtime() is a method. This required turning some of Orendorff's properties into methods.

The actual FSPath class ended up closer to Orendorff's original than I had intended, because several of the planned innovations (from python-3000 suggestions, Raphael's alternative path class, and my own mind) turned to be not necessarily superior in actual programs, whereas Orendorff's methods have proven themselves reliable in production systems for three years now, so I deferred to them when in doubt.

The biggest such move was making FSPath a subclass of Path. Originally I had tried to make them unrelated classes (FSPath containing a Path), but this became unworkable in the implementation due to the constant need to call both types of methods. (Say you have an FSPath directory and you need to join a filename to it and then delete the file; do you really want to convert from FSPath to Path and back again? Do you really want to write "FSPath(Path(my_fspath.path, 'foo'))"?) So one class is better than two, even if the BDFL disapproves. I opted for the best of both worlds via inheritance, so those who want one class can pretend it is, and those who want two classes can get a warm fuzzy feeling that they're defined separately. (They can even ignore FSPath and use Path with os.* functions if they prefer.) If Path is someday accepted into the standard libary, FSPath will become a subclass of that. And others can subclass FSPath or write an alternative if they don't like my API.

I also intended to put all non-trivial code into generic functions that third-party path libraries could call. But that also became unworkable due to the tight integration that naturally occurs between the methods, one calling another. What's really needed now is for FSPath to get into the real world so we can see which generic code actually is valuable, and then those can be factored out later.

.stem is called stem because "namebase" can be confused with os.path.basename(), "name_without_ext" is too wordy, and "name_no_ext" is looks like bad English.

All method names have underscores between words except those starting with "is", "mk", "rm", and "stat". The "is" methods are so highly used that deviating from the os.path/Orendorff spelling would trip up a lot of programmers, including me. "mk" and "rm" I just like. (Be glad I didn't rename .copy_tree to "cptree" to match .rmtree.) (or ".drive" and ".unc" properties) are not needed. They may be added if they prove necessary, but then how do you get "everything except the drive" or "everything except the UNC prefix". I also had to move the slash following the UNC prefix to the prefix itself, to maintain the rule that everything after the first component is a relative path.

I tried making a smart stat object so that one could do "p.stat().size" and "p.stat().isdir". This was one of the proposals for Raphael's class, to get rid of a bunch of top-level methods and obviate the need for a set of "l" methods covering the "stat" and "lstat" operations. I also made a phony stat object if the path didn't exist, to hang the ".exists" attribute off. But I was so used to typing p.isdir() etc from Orendorff that I couldn't adjust. And Python has only one "l" function anyway, os.path.lexists(). And I didn't want to write the stat object in C, meaning every stat would incur Python overhead to convert the result attributes. So in the end I decided to keep the methods shadowing the os.path convenience functions, remove the "get" prefix from the "get" methods ("getmtime"), and let .stat and .statvfs return the Python default object. I'm still tempted to make .stat() and .statvfs return None if the path doesn't exist (rather than raising OSError), but I'm not sure that's necessarily better so I held off on that. Presumably one wouldn't use .stat() that much anyway since the other methods are more convenient.

.components() comes from Raphael's class, the concept of treating paths as a list of components, with the first component being the filesystem root (for an absolute path). This required unifying Posix and Windows roots into a common definition. .split_root() handles drive paths and UNC paths, so "splitdrive" and "splitunc" (or ".drive" and ".unc" properties) were deemed unnecessary. They may be added later if needed. One problem with ".drive" and ".unc" properties is how to specify "everything except the drive" and "everything except the UNC prefix", which are needed to recreate the path or derive a similar path. The slash after the UNC prefix was also moved to the prefix, to maintain the rule that all components after the first make a relative path.

"Components" turned out to be a useful way to convert paths from one platform to another, which was one of Talin's requests. However, what Talin really wanted was to put Posix paths in a config file and have them translate to the native platform. Since .norm() and .norm_case() already do this on Windows, it's questionable how much cross-platform support is really necessary. Especially since macpath is obsolete now that Mac OS X uses Posix, and Mac OS 9 is about to be dropped from Python. So the multi-platform code is probational.

Joining paths is done via the constructor, which takes multiple positional arguments. This was deemed as better than Orendorff's ".joinpath" method for reasons I'm not sure of.

.child() was requested by Glyph, to create safe subpaths that can never reach outside their parent directory even if based on untrusted user strings. It's also sneaky way to do "joinpath" when you're really prefer to use a method rather than the costructor, as long as each component has to be passed as a separate argument.

Orendorff has ".listdir", ".dirs", and ".files" methods (non-recursive), and ".walk", ".walkdirs", and "walkfiles" (recursive). Raphael has one ".glob" method to rule them all. I went back and forth on this several times and finally settled on .listdir (non-recursive) and .walk (recursive), with a 'filter' argument to return only files or directories. Neither Orendorff nor Raphael nor os.walk handle symlinks adequately in my opinion: sometimes you want to exclude symlinks and then list them separately. .listdir has a 'names_only' option to make it return just the filenames like os.listdir, because sometimes that's what you need, and there's no reason to create paths you're just going to unpack again anyway. .listdir and .walk are separate methods because implementing them as one is complicated -- they have so many contingencies. .listdir() and .listdir(names_only=True) are the same method because I couldn't come up with a better name for the former. I dropped the name "glob" because it's meaningless to non-Unix users.

.absolute, .relative, and .resolve are hopefully better named than Orendorff's "abspath", "relpath", and "realpath", which were taken directly from os.path. .hardlink is so-named because it's less used than .symlink nowadays, and a method named ".link" is easy to misinterpret.

I wanted a symbolic syntax for .chmod ("u=rwx,g+w") and a companion function to parse a numeric mode, and user names/group names for .chown, but those were deferred to get the basic classes out the door. The methods take the same arguments as their os counterparts.

Unipath-0.2.1/BUGS.txt0000644000175000017500000000010111013773726012600 0ustar msomsoMethods inherited from unicode return strings rather than paths. Unipath-0.2.1/CHANGES0000644000175000017500000000154511014371061012272 0ustar msomso0.2.1 - Delete spurious references to deleted ``unipath.platform`` package. 0.2.0 - Rename Path to AbstractPath, and FSPath to Path. FSPath remains as an alias for backward compatibility. - Allow integers in constructor. - Path.mkdir() checks whether the directory exists first. - Test suite now uses nose instead of unittest. - "+" operator returns concatenated path rather than string. - Bugfix in Path.rel_path_to(). - Thanks to Roman for patches and suggestions. - Delete Path.symlink(); use Path.write_link() instead -- note that the arg is the desination rather than the source! - Path.make_relative_link_to() is a shortcut for ``self.write_link(self.rel_path_to(dst))``. - Delete the ``platform`` package. See the tests if you need non-native path syntax.` 0.1.0, released 2007-01-28 by MSO - Initial release. Unipath-0.2.1/Unipath.egg-info/0000755000175000017500000000000011014371227014400 5ustar msomsoUnipath-0.2.1/Unipath.egg-info/SOURCES.txt0000644000175000017500000000037711014371227016273 0ustar msomsoREADME.txt setup.py Unipath.egg-info/PKG-INFO Unipath.egg-info/SOURCES.txt Unipath.egg-info/dependency_links.txt Unipath.egg-info/top_level.txt unipath/__init__.py unipath/abstractpath.py unipath/errors.py unipath/path.py unipath/test.py unipath/tools.py Unipath-0.2.1/Unipath.egg-info/dependency_links.txt0000644000175000017500000000000111014371227020446 0ustar msomso Unipath-0.2.1/Unipath.egg-info/top_level.txt0000644000175000017500000000001011014371227017121 0ustar msomsounipath Unipath-0.2.1/Unipath.egg-info/PKG-INFO0000644000175000017500000000634011014371227015500 0ustar msomsoMetadata-Version: 1.0 Name: Unipath Version: 0.2.1 Summary: Object-oriented alternative to os/os.path/shutil Home-page: http://sluggo.scrapping.cc/python/unipath/ Author: Mike Orr Author-email: sluggoster@gmail.com License: Python Download-URL: http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.1.tar.gz Description: Unipath is an object-oriented approach to file/pathname manipulations and filesystem calls, an alternative to ``os.path.*``, ``shutil.*``, and some ``os.*`` functions. It's based on Orendorff's path.py but has been refactored to make application code more concise, by focusing on what the programmer wants to do rather than on low-level operations exactly like the C library. For instance: - ``p.mkdir()`` succeeds silently if the directory already exists, and - ``p.mkdir(True)`` creates intermediate directories a la ``os.makedirs``. - ``p.rmtree(parents=True)`` combines ``shutil.rmtree``, ``os.path.isdir``, ``os.remove``, and ``os.removedirs``, to recursively remove whatever it is if it exists. - ``p.read_file("rb")`` returns the file's contents in binary mode. - ``p.needs_update([other_path1, ...])`` returns True if p doesn't exist or has an older timestamp than any of the others. - extra convenience functions in the ``unipath.tools`` module. ``dict2dir`` creates a directory hierarchy described by a ``dict``. ``dump_path`` displays an ASCII tree of a directory hierarchy. Unipath has a ``Path`` class for abstract pathname manipulations (``p.parent``, ``p.expand()``), and a ``FSPath`` subclass for filesystem calls (all the ones above). You can do "from unipath import FSPath as Path" and forget about the distinction, or use the ``Path`` class and be confident you'll never access the filesystem. The ``Path`` class is also being proposed as an addition to the standard libary (``os.path.Path``). Compare:: # Reference a file that's two directories above another file. p = os.path.join(os.path.dirname(os.path.dirname("/A/B/C")), "file.txt") p = Path("A/B/C").parent.parent.child("file.txt") p = Path("A/B/C").ancestor(2).child("file.txt") p0 = Path("/A/B/C"); p = Path(p0.parent.parent, "file.txt") # Change the extension of a path. p = os.path.splitext("image.jpg")[0] + ".png" p = Path("image.jpg").name + ".png" Documentation is in the README and on the `website `__. Unipath is in early alpha release so the API may change as it get greater use in the "real world". Unipath comes with extensive unittests, and has been tested on Python 2.5 and 2.4.4 on Linux. Feedback and Windows/Macintosh testers are encouraged. Keywords: os.path filename pathspec path files directories filesystem Platform: UNKNOWN Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Operating System :: OS Independent Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Utilities Unipath-0.2.1/PKG-INFO0000644000175000017500000000634011013773726012407 0ustar msomsoMetadata-Version: 1.0 Name: Unipath Version: 0.1.0 Summary: Object-oriented alternative to os/os.path/shutil Home-page: http://sluggo.scrapping.cc/python/unipath/ Author: Mike Orr Author-email: sluggoster@gmail.com License: Python Download-URL: http://sluggo.scrapping.cc/python/unipath/Unipath-0.1.0.tar.gz Description: Unipath is an object-oriented approach to file/pathname manipulations and filesystem calls, an alternative to ``os.path.*``, ``shutil.*``, and some ``os.*`` functions. It's based on Orendorff's path.py but has been refactored to make application code more concise, by focusing on what the programmer wants to do rather than on low-level operations exactly like the C library. For instance: - ``p.mkdir()`` succeeds silently if the directory already exists, and - ``p.mkdir(True)`` creates intermediate directories a la ``os.makedirs``. - ``p.rmtree(parents=True)`` combines ``shutil.rmtree``, ``os.path.isdir``, ``os.remove``, and ``os.removedirs``, to recursively remove whatever it is if it exists. - ``p.read_file("rb")`` returns the file's contents in binary mode. - ``p.needs_update([other_path1, ...])`` returns True if p doesn't exist or has an older timestamp than any of the others. - extra convenience functions in the ``unipath.tools`` module. ``dict2dir`` creates a directory hierarchy described by a ``dict``. ``dump_path`` displays an ASCII tree of a directory hierarchy. Unipath has a ``Path`` class for abstract pathname manipulations (``p.parent``, ``p.expand()``), and a ``FSPath`` subclass for filesystem calls (all the ones above). You can do "from unipath import FSPath as Path" and forget about the distinction, or use the ``Path`` class and be confident you'll never access the filesystem. The ``Path`` class is also being proposed as an addition to the standard libary (``os.path.Path``). Compare:: # Reference a file that's two directories above another file. p = os.path.join(os.path.dirname(os.path.dirname("/A/B/C")), "file.txt") p = Path("A/B/C").parent.parent.child("file.txt") p = Path("A/B/C").ancestor(2).child("file.txt") p0 = Path("/A/B/C"); p = Path(p0.parent.parent, "file.txt") # Change the extension of a path. p = os.path.splitext("image.jpg")[0] + ".png" p = Path("image.jpg").name + ".png" Documentation is in the README and on the `website `__. Unipath is in early alpha release so the API may change as it get greater use in the "real world". Unipath comes with extensive unittests, and has been tested on Python 2.5 and 2.4.4 on Linux. Feedback and Windows/Macintosh testers are encouraged. Keywords: os.path filename pathspec path files directories filesystem Platform: UNKNOWN Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Operating System :: OS Independent Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Utilities Unipath-0.2.1/setup.py0000644000175000017500000000620211014371110012777 0ustar msomsofrom distutils.core import setup VERSION = "0.2.1" DESCRIPTION = """\ Unipath is an object-oriented approach to file/pathname manipulations and filesystem calls, an alternative to ``os.path.*``, ``shutil.*``, and some ``os.*`` functions. It's based on Orendorff's path.py but has been refactored to make application code more concise, by focusing on what the programmer wants to do rather than on low-level operations exactly like the C library. For instance: - ``p.mkdir()`` succeeds silently if the directory already exists, and - ``p.mkdir(True)`` creates intermediate directories a la ``os.makedirs``. - ``p.rmtree(parents=True)`` combines ``shutil.rmtree``, ``os.path.isdir``, ``os.remove``, and ``os.removedirs``, to recursively remove whatever it is if it exists. - ``p.read_file("rb")`` returns the file's contents in binary mode. - ``p.needs_update([other_path1, ...])`` returns True if p doesn't exist or has an older timestamp than any of the others. - extra convenience functions in the ``unipath.tools`` module. ``dict2dir`` creates a directory hierarchy described by a ``dict``. ``dump_path`` displays an ASCII tree of a directory hierarchy. Unipath has a ``Path`` class for abstract pathname manipulations (``p.parent``, ``p.expand()``), and a ``FSPath`` subclass for filesystem calls (all the ones above). You can do "from unipath import FSPath as Path" and forget about the distinction, or use the ``Path`` class and be confident you'll never access the filesystem. The ``Path`` class is also being proposed as an addition to the standard libary (``os.path.Path``). Compare:: # Reference a file that's two directories above another file. p = os.path.join(os.path.dirname(os.path.dirname("/A/B/C")), "file.txt") p = Path("A/B/C").parent.parent.child("file.txt") p = Path("A/B/C").ancestor(2).child("file.txt") p0 = Path("/A/B/C"); p = Path(p0.parent.parent, "file.txt") # Change the extension of a path. p = os.path.splitext("image.jpg")[0] + ".png" p = Path("image.jpg").name + ".png" Documentation is in the README and on the `website `__. Unipath is in early alpha release so the API may change as it get greater use in the "real world". Unipath comes with extensive unittests, and has been tested on Python 2.5 and 2.4.4 on Linux. Feedback and Windows/Macintosh testers are encouraged. """ setup( name="Unipath", version=VERSION, description="Object-oriented alternative to os/os.path/shutil", long_description=DESCRIPTION, author="Mike Orr", author_email="sluggoster@gmail.com", url="http://sluggo.scrapping.cc/python/unipath/", download_url= "http://sluggo.scrapping.cc/python/unipath/Unipath-%s.tar.gz" % VERSION, packages=["unipath"], license="Python", #platform="Multiplatform", keywords="os.path filename pathspec path files directories filesystem", classifiers=[ "License :: OSI Approved :: Python Software Foundation License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Utilities", ], )