Skip to content

Instantly share code, notes, and snippets.

@sodre
Created June 7, 2019 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sodre/d948bf09f772300fee2b948127c56537 to your computer and use it in GitHub Desktop.
Save sodre/d948bf09f772300fee2b948127c56537 to your computer and use it in GitHub Desktop.
Overlay's files on an existing path, overwriting anything that it finds.
#!/usr/bin/env python
# A Python function for overlaying a source directory on top of a destination dir
import os
import shutil
import re
def normalize_paths(dest_prefix, src, dest):
dest = re.sub(r'^/+', '', dest)
return (
os.path.abspath(src),
os.path.join(dest_prefix, dest)
)
def overlay(dest_prefix, src, dest):
abs_src, abs_dest = normalize_paths(dest_prefix, src, dest)
if os.path.isfile(abs_src):
return overlay_file(abs_src, abs_dest)
elif os.path.isdir(abs_src):
return overlay_dir(abs_src, abs_dest)
def overlay_file(src_file, dest):
if dest.endswith('/'):
dest_file=os.path.join(dest,os.path.basename(src_file))
else:
dest_file = dest
dest_dir = os.path.dirname(dest_file)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
print("{} -> {}".format(src_file, dest_file))
shutil.copy2(src_file, dest_file)
def overlay_dir(abs_src, abs_dest):
for root, dirs, files in os.walk(abs_src):
dest_root=os.path.normpath(root.replace(abs_src, abs_dest))
if not os.path.exists(dest_root):
os.mkdir(dest_root)
for f in files:
src_file=os.path.join(root, f)
dest_file=os.path.join(dest_root, f)
print("{} -> {}".format(src_file, dest_file))
shutil.copy2(src_file, dest_file)
if __name__ == "__main__":
# The conda-build dir is spatted to PREFIX/
# overlay("/tmp/tmp0", "/Users/sodre/git/conda/conda-build", "/")
# The overlay-dir.py file is copied to PREFIX/overlay-dir.py
overlay("/tmp/tmp1", 'overlay-dir.py', '/')
# The overlay-dir.py file is copied to PREFIX/bin/overlay-dir.py
overlay("/tmp/tmp2", 'overlay-dir.py', '/bin/')
# The overlay-dir.py file is copied to PREFIX/bin/overlay
overlay("/tmp/tmp3", 'overlay-dir.py', '/bin/overlay')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment