# cmdlet.py # Copyright (C) 2008 Michael Foord # E-mail: fuzzyman AT voidspace DOT org DOT uk import os import System __version__ = '0.1.0' __all__ = ['Action', 'Cmdlet', 'ignored', 'listdir', 'notolderthan', 'prettyprint'] ignored = object() class Cmdlet(list): def __init__(self, function, _populated=False): self.function = function self._populated = _populated def __call__(self, *args, **keywargs): return Cmdlet(self.function(*args, **keywargs)) def __rshift__(self, other): data = self if not self._populated: # TODO: the first function must return a list ? data = self.function() new = Cmdlet(other.function, True) vals = [other.function(m) for m in data] new[:] = [v for v in vals if v is not ignored] return new def __rrshift__(self, other): new = Cmdlet(self.function, True) vals = [self.function(m) for m in other] new[:] = [v for v in vals if v is not ignored] return new def __repr__(self): return 'Cmdlet(%s)' % list.__repr__(self) class Action(Cmdlet): def __rshift__(self, other): Cmdlet.__rshift__(self, other) return None def __repr__(self): return 'Action(%s)' % self.function.__name__ class Path(object): def __init__(self, path, entry): self.dir = path self.name = entry self.path = os.path.join(path, entry) self.mtime = System.IO.File.GetCreationTime(self.path) self.ctime = System.IO.File.GetLastWriteTime(self.path) def __repr__(self): start = 'File:' if os.path.isdir(self.path): start = 'Dir:' ctime = self.ctime mtime = self.mtime return "%s %s :ctime: %s :mtime: %s" % (start, self.path, ctime, mtime) def f_listdir(path): def listdir(): return [Path(path, member) for member in os.listdir(path)] return listdir def f_notolderthan(date): datetime = System.DateTime.Parse(date) def notolderthan(member): if member.mtime >= datetime: return member return ignored return notolderthan def f_prettyprint(val): print val f_prettyprint.__name__ = 'prettyprint' listdir = Cmdlet(f_listdir) notolderthan = Cmdlet(f_notolderthan) prettyprint = Action(f_prettyprint) if __name__ == '__main__': # Prints all the paths in the current directory younger than the third of February print 'First test' listdir('.') >> notolderthan('2/3/08') >> prettyprint def recursive_walk(path): for e in os.listdir(path): p = os.path.join(path, e) if os.path.isfile(p): yield Path(path, e) else: for entry in recursive_walk(p): yield entry print print 'Passing in a generator' recursive_walk('.') >> notolderthan('2/3/08') >> prettyprint