-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathautocatalog.py
executable file
·80 lines (63 loc) · 2.64 KB
/
autocatalog.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/bin/env python3
import os
import argparse
def create_argparser():
class HelpFormatter(argparse.RawDescriptionHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):
""" Dummy class for RawDescription and ArgumentDefault formatter """
description = "Automatically catalog large directories for ingestion into CVMFS"
epilog = ""
parser = argparse.ArgumentParser(prog="autocatalog",
formatter_class=HelpFormatter,
description=description,
epilog=epilog)
parser.add_argument("--path", required=True, default=None, help="Root path to automatically catalog")
parser.add_argument("--size", default=20000, help="Number of items in a folder beyond which a catalog is created")
parser.add_argument("--dry-run", action='store_true', help="Dry run")
return parser
def main():
args = create_argparser().parse_args()
path = args.path
size = int(args.size)
tree = {}
roots = []
dirs_in_root = []
nelems = []
for root, dirs, files in os.walk(path):
tree[root] = {'dirs': dirs, 'nelems': len(dirs) + len(files)}
large_subdirs = extract_large_subdirs(path, tree, size)
for k, v in large_subdirs.items():
# create empty ".cvmfscatalog" file in the sub-directory
catalog_file = os.path.join(k, ".cvmfscatalog")
if args.dry_run:
print("[DRY RUN]: Creating %s" % catalog_file)
else:
print("Creating %s" % catalog_file)
with open(catalog_file, 'w') as fp:
pass
def total_count(path, tree):
matches = list(filter(lambda x: x.startswith(path), tree.keys()))
count = sum([tree[x]['nelems'] for x in matches])
return count
def counts_in_subdirs(path, tree):
counts = {}
if path not in tree or 'dirs' not in tree[path]:
return counts
for x in tree[path]['dirs']:
subpath = os.path.join(path, x)
counts[subpath] = total_count(subpath, tree)
return counts
def extract_large_subdirs(path, tree, size):
# add dir to list if its total_count is above size and it contains no directory that is above size
# else, go down one level
root_count = total_count(path, tree)
sub_counts = counts_in_subdirs(path, tree)
large_subdirs = {k: v for k, v in sub_counts.items() if v > size}
if root_count > size and not large_subdirs:
return {path: root_count}
else:
results = {}
for k, v in large_subdirs.items():
results.update(extract_large_subdirs(k, tree, size))
return results
if __name__ == "__main__":
main()