Skip to content

Instantly share code, notes, and snippets.

@dro248
Last active June 18, 2018 14:29
Show Gist options
  • Save dro248/798fc163e014090233983bfd1b6c2db1 to your computer and use it in GitHub Desktop.
Save dro248/798fc163e014090233983bfd1b6c2db1 to your computer and use it in GitHub Desktop.
Clones the structure of another directory
import os
import sys
import shutil
import logging
class DirectoryCloner:
"""
This class recursively creates a mirrored directory
with the same structure as the directory passed in.
"""
def __init__(self, directory):
"""
- Creates the DirectoryCloner object and begins the cloning process.
- Test: directory path exists
- Test: directory is directory
:param directory: the directory to be cloned
"""
if not os.path.exists(os.path.abspath(directory)):
logging.error("'{dir}' does not exist.".format(dir=os.path.abspath(directory)))
raise ValueError
if not os.path.isdir(directory):
logging.error("'{dir}' is not a directory.".format(dir=os.path.abspath(directory)))
raise ValueError
# Working case
else:
abs_path = os.path.abspath(directory)
# self.cwd : current working directory
# self.mirror_wd : the working directory that is being created (starts off being the same as cwd)
# self.directory : name (only) of directory we want to clone
self.cwd = os.path.abspath(os.path.join(abs_path, os.pardir))
self.mirror_wd = self.cwd
self.directory = abs_path.split('/')[-1]
self.delete_shadow_dir(os.path.join(self.cwd, '_' + self.directory))
self.rec_clone(self.directory, self.cwd, self.mirror_wd)
@staticmethod
def delete_shadow_dir(absolute_path):
"""
Deletes the shadow directory (if it exists)
:param absolute_path: The absolute path to the shadow directory
:return: None
"""
if os.path.exists(absolute_path):
shutil.rmtree(absolute_path)
@classmethod
def rec_clone(self, dir, orig_wd, mirror_wd):
"""
Recursively clones the real directory
:param dir: The directory that we are currently cloning from the real working directory (orig_wd)
:param orig_wd: The current working directory containing our "dir" param
:param mirror_wd: The current working directory containing our shadow directory
:return: None
"""
# if we're at the root level, add an underscore to the beginning of shadow directory
mirror_wd = os.path.join(mirror_wd, "_" + dir) if dir == self.directory else os.path.join(mirror_wd, dir)
orig_wd = os.path.join(orig_wd, dir)
# Create directory if it doesn't exist
if not os.path.exists(mirror_wd):
os.makedirs(mirror_wd)
# Search for subdirectories
for file in os.listdir(orig_wd):
if os.path.isdir(os.path.join(orig_wd, file)):
self.rec_clone(file, orig_wd, mirror_wd)
if __name__ == "__main__":
if len(sys.argv) > 1:
x = DirectoryCloner(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment