|
| 1 | +import os |
| 2 | +import shutil |
| 3 | + |
| 4 | +from contextlib import contextmanager |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | + |
| 8 | +@contextmanager |
| 9 | +def copy_work(working_dir, text_to_replace, replacement_text): |
| 10 | + """ |
| 11 | + Recursive function that iterates down through source directory until a file is reached. If file is newer than same |
| 12 | + file in the target directory then replaces target file with source version. If source doesn't exist in target |
| 13 | + directory then copies source file into target directory. |
| 14 | + :param replacement_text: replacement text to put into source path i.e /a/b/<replacement_text>/file |
| 15 | + :param text_to_replace: text that needs to be replaced in source path i.e /a/b/<text_to_replace>/file |
| 16 | + :param working_dir: the source directory that contains the newest files. |
| 17 | + :return: copied file |
| 18 | + """ |
| 19 | + os.chdir(working_dir) |
| 20 | + for file in Path.cwd().iterdir(): |
| 21 | + if file.is_file(): |
| 22 | + try: |
| 23 | + p1, p2 = os.path.getmtime(Path(file.as_posix())), os.path.getmtime(Path( |
| 24 | + f'{os.path.split(file.as_posix())[0].replace(text_to_replace, replacement_text)}/{os.path.split(file.as_posix())[1]}').as_posix()) |
| 25 | + if p1 > p2: |
| 26 | + shutil.copy(Path(file).as_posix(), Path( |
| 27 | + f'{os.path.split(file.as_posix())[0].replace(text_to_replace, replacement_text)}/{os.path.split(file.as_posix())[1]}')) |
| 28 | + print(f'{Path(file).name} replaced.') |
| 29 | + except: |
| 30 | + shutil.copy(Path(file).as_posix(), Path( |
| 31 | + f'{os.path.split(file.as_posix())[0].replace(text_to_replace, replacement_text)}/{os.path.split(file.as_posix())[1]}')) |
| 32 | + print(f'{Path(file).name} added.') |
| 33 | + else: |
| 34 | + copy_work(file, text_to_replace, replacement_text) |
| 35 | + |
0 commit comments