Last active
December 13, 2015 22:19
-
-
Save mpenkov/4983500 to your computer and use it in GitHub Desktop.
cp with regular expression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Behaves pretty much like cp -Pruv , except supports skipping directories. | |
Copy one directory to another recursively. If any subdirectories match a | |
specified regular expression pattern, they are not copied. | |
Also, directories containing a file called .nobackup are not backup up. | |
""" | |
import os | |
import os.path as P | |
import re | |
import shutil | |
import stat | |
def nightly_backup(source, dest, skip_regex): | |
stack = [ P.abspath(source) ] | |
while stack: | |
from_dir = stack.pop() | |
contents = os.listdir(from_dir) | |
if ".nobackup" in contents: | |
continue | |
rel_dirpath = P.relpath(from_dir, source) | |
to_dir = P.join(dest, rel_dirpath) | |
if not P.isdir(to_dir): | |
os.mkdir(to_dir) | |
for name in contents: | |
from_path = P.join(from_dir, name) | |
to_path = P.join(to_dir, name) | |
if skip_regex.match(from_path) or P.islink(from_path): | |
continue | |
if P.isdir(from_path): | |
stack.append(from_path) | |
else: | |
if P.exists(to_path): | |
if P.getmtime(from_path) < P.getmtime(to_path): | |
continue | |
# | |
# if a file is read-only, then shutil.copy will fail to | |
# overwrite it. delete it here to be safe. | |
# | |
os.remove(to_path) | |
print "`%s' -> `%s'" % (from_path, to_path) | |
shutil.copy(from_path, to_path) | |
if __name__ == "__main__": | |
import sys | |
regex = re.compile(""" | |
^/home/misha/\.anki | | |
^/home/misha/samba | | |
^/home/misha/\.cache | | |
^/home/misha/Desktop | | |
^/home/misha/Downloads | | |
^/home/misha/.dropbox | | |
^/home/misha/Dropbox | | |
^/home/misha/nobackup | | |
^/home/misha/.local/share/trash | | |
^/home/misha/Music | | |
^/home/misha/Pictures | | |
^/home/misha/Pictures2 | | |
^/home/misha/src | | |
^/home/misha/tmp | | |
^/home/misha/\.thumbnails | | |
^/home/misha/\.Trash | | |
^/home/misha/Videos | | |
^/home/misha/\.gvfs | |
""", re.VERBOSE) | |
nightly_backup("/home/misha", "/home/misha/samba/nightly-backup", regex) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment