Source

backup-with-timestamp / backup-with-timestamp

Full commit
#!/usr/bin/env python
### -*- coding: utf-8; -*-

__rcsid__ = '$Id$'

timeformat = '%Y%m%dT%H%M%S%z'

import sys, os, shutil
from stat import *
from datetime import *

import time as _time
class _tzinfo(tzinfo):
    def __init__(self):
        self.zero = timedelta(0)
        self.stdoffset = timedelta(seconds = -_time.timezone)
        if _time.daylight:
            self.dstoffset = timedelta(seconds = -_time.altzone)
        else:
            self.dstoffset = self.stdoffset
            self.dstdiff = self.dstoffset - self.stdoffset
    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, -1)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return(tt.tm_isdst > 0)
    def utcoffset(self, dt):
        if self._isdst(dt):
            return(self.dstoffset)
        else:
            return(self.stdoffset)
    def dst(self, dt):
        if self._isdst(dt):
            return(self.dstdiff)
        else:
            return(self.zero)
    def tzname(self, dt):
        tzname = _time.tzname[self._isdst(dt)]
        return(tzname)

def generate_backupname(pathname, format):
    mtime = datetime.fromtimestamp(os.lstat(pathname).st_mtime, _tzinfo())
    return(pathname + "." + mtime.strftime(format))

def main(args):
    for file in args:
        try:
            if os.path.isdir(file):
                raise OSError(21, "Is a directory")
            backup = generate_backupname(file, timeformat)
            shutil.move(file, backup)
            sys.stdout.write("`%s' -> `%s'\n" % (file, backup))
            shutil.copy2(backup, file)
            sys.stdout.write("`%s' -> `%s'\n" % (backup, file))
        except OSError, (errno, errstr):
            sys.stderr.write("%s: %s: %s\n" % (sys.argv[0], file, errstr))
        except IOError, (errno, errstr):
            sys.stderr.write("%s: %s: %s\n" % (sys.argv[0], backup, errstr))

if __name__ == "__main__":
    main(sys.argv[1:])