public
Created

Small script to copy the difference between two folders to a new folder

  • Download Gist
diffFolders.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#!/usr/bin/env python
 
import os
import os.path
import sys
import shutil
 
# Bugfixed version of makedirs
def makedirs(name, mode=0777):
"""makedirs(path [, mode=0777])
 
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist. This is
recursive.
 
"""
head, tail = os.path.split(name)
if not tail:
head, tail = os.path.split(head)
if head and tail and not os.path.exists(head):
try:
makedirs(head, mode)
except OSError, e:
# be happy if someone already created the path
if e.errno != errno.EEXIST:
raise
if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists
return
# Bugfix: Don't fail if directory exists
if not os.path.exists(name):
os.mkdir(name, mode)
 
os.makedirs = makedirs
 
class DiffFolders:
def run(self, args):
src1 = os.path.abspath( args[0] )
src2 = os.path.abspath( args[1] )
dest = os.path.abspath( args[2] )
 
if not os.path.exists(src1):
raise Exception('Missing source folder %s' % src1)
if not os.path.exists(src2):
raise Exception('Missing source folder %s' % src2)
 
if os.path.exists(dest):
print 'Deleting %s' % dest
shutil.rmtree(dest)
 
def ignore(folder, content):
if folder.startswith(src1):
prefix = src2
relpath = os.path.relpath(folder, src1)
else:
prefix = src1
relpath = os.path.relpath(folder, src2)
 
result = []
for entry in content:
path = os.path.join(folder, entry)
if os.path.isdir(path):
continue
 
if not os.path.isfile(path):
raise Exception('Can only handle files: %s' % path)
 
otherPath = os.path.join(prefix, relpath, entry)
if os.path.exists(otherPath):
if not os.path.isfile(otherPath):
raise Exception('Expected two files:\n%s\n%s' % (path, otherPath))
result.append( entry )
return result
 
shutil.copytree(src1, dest, ignore=ignore)
shutil.copytree(src2, dest, ignore=ignore)
 
if __name__ == '__main__':
DiffFolders().run(sys.argv[1:])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.