Tuesday, January 13, 2009

safecp

After destroying an rc.lua for Awesome, I was motivated to write this simple script. It skips overwriting all files, unlike cp:

safecp

#!/usr/bin/python
from os import path
from sys import stderr, exit, argv
from shutil import copy, copytree

copymethod = copy
if len(argv) == 3:
src, dest = argv[1:3]
src, dest = unicode(src, 'utf8'), unicode(dest, 'utf8')
if path.exists(src):
if path.isdir(src):
print >>stderr, u'Copying directory recursively:', src
copymethod = copytree
if (not path.exists(dest)) or path.isdir(dest):
copymethod(src, dest)
else:
print >>stderr, u'Not overwriting existing file:', dest
exit(3)
else:
print >>stderr, u'File not found:', src
exit(2)
elif len(argv) > 3:
dest = unicode(argv.pop(), 'utf8')
src = argv[1:]
if path.isdir(dest):
for s in src:
s = unicode(s, 'utf8')
copymethod = copy
target = path.join(dest, path.basename(s))
if path.isdir(s):
print >>stderr, u'Copying directory recursively:', s
copymethod = copytree
if not path.exists(target):
copymethod(s, target)
else:
print >>stderr, u'Not overwriting existing file or directory:', target
else:
print >>stderr, u'Destination must be directory:', dest
exit(2)
else:
print >>stderr, u'Usage: %s src1 [ src2 [ src3 [ ... ]]] dest' % argv[0]
exit(1)

No comments: