-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflatten_dir.py
61 lines (52 loc) · 1.91 KB
/
flatten_dir.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import os
import sys
import shutil
import argparse
from pathlib import Path
def flatten_dir(target_dir, destination, options):
for child in target_dir.iterdir():
if child.is_dir():
flatten_dir(child, destination, options)
if (
options.delete
and not options.dry_run
and child != target_dir
and child != destination
and not any(child.iterdir()) # is the dir empty?
):
child.rmdir()
else:
if child.parent != destination:
transport = Path(destination, child.name)
if not options.dry_run:
if options.delete:
child.rename(transport)
else:
shutil.copy(child, transport)
if options.log:
action_log_symbol = '-->' if options.delete else '<->'
print(f'{child} {action_log_symbol} {transport}')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Flatten a directory tree.')
parser.add_argument(
'target',
type=Path,
metavar='<target-directory>',
help='the directory to flatten (defaults to current environment directory)')
parser.add_argument(
'--dry-run',
action='store_true',
help='do a test run of the file operations without modifying any files')
parser.add_argument(
'--no-log',
action='store_false',
dest='log',
help='supress output of file operations')
parser.add_argument(
'--no-delete',
dest='delete',
action='store_false',
help='prevent the original tree subfolders from being deleted')
args = parser.parse_args()
absolute_target = args.target.resolve()
flatten_dir(absolute_target, absolute_target, args)