[ale] Archiving directories/files with "compressed" mirror version

Brian Pitts brian at polibyte.com
Thu Aug 14 01:44:47 EDT 2008


Brian Pitts wrote:
> Chris Woodfield wrote:
>> I'm handling a request that I'd be surprised if no one's run into  
>> before, so I figured I'd
>>
>> The request is to be able to walk a directory tree and make a mirrored  
>> copy of the directory, but with every file compressed. Not make a  
>> single archive of the dir - the end result will have all directories  
>> with the same names, perms, etc, but each file will be a bzip'ed  
>> version of the original.

Here's another version that's a hopefully a little clearer and actually
maintains the uid/gid/permissions.

#!/usr/bin/env python

import sys, os, bz2
import os.path as path;

if len(sys.argv) != 2:
  print 'Specify one source directory'
  sys.exit()

source = path.abspath(sys.argv[1])
dest = source + '.archive'
os.mkdir(dest)

for root, dirs, files in os.walk(source, topdown=True):
  for name in dirs:
    newroot = root.replace(source, dest)
    oldpath = path.join(root, name)
    newpath = path.join(newroot, name)
    statinfo = os.stat(oldpath)
    os.mkdir(newpath, statinfo.st_mode)
    os.chown(newpath, statinfo.st_uid, statinfo.st_gid)
  for name in files:
    newroot = root.replace(source, dest)
    newname = name + '.bz2'
    oldpath = path.join(root, name)
    newpath = path.join(newroot, newname)
    ifile = open(oldpath)
    ofile = bz2.BZ2File(newpath, 'w')
    ofile.writelines(ifile)
    ofile.close()
    ifile.close()
    statinfo = os.stat(oldpath)
    os.chmod(newpath, statinfo.st_mode)
    try:
      os.chown(newpath, statinfo.st_uid, statinfo.st_gid)
    except:
      print "Unable to change the uid or gid of %s" % newpath


More information about the Ale mailing list