-
Notifications
You must be signed in to change notification settings - Fork 1
/
removeDups.py
131 lines (104 loc) · 3.01 KB
/
removeDups.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import os
from itertools import permutations
import shutil
import re
import string
from . import utils as u
# from pdb import set_trace
files = []
def getFiles(fold):
global files
for i in os.listdir(fold):
new = fold + '/' + i
if os.path.isfile(new):
files.append(new)
else:
getFiles(new)
def regexify(name):
regex_special_chars = '.!$^*()[]|+}\\{'
new_name = ''
for char in name:
if char in regex_special_chars:
new_name += '\\'+char
else:
new_name += char
print(new_name)
return new_name
def isDup(f1, f2):
# filename without extension
copy = u.is_dup(f1, f2)
if copy:
key = f2 if f1 == copy else f1
print(key)
re_ptrn = re.compile(rf'^({key}(\s\([1-10]))+)$')
try:
if (re_ptrn.findall(copy)[0][0]):
return 1
except Exception as e:
pass
return 0
def merge_items_and_delete(main_fold, copy_folders: list):
for fold in copy_folders:
for item in os.listdir(fold):
try:
shutil.copy(fold + '/' + item, main_fold)
except Exception as e:
continue
print('deleting', fold)
try:
shutil.rmtree(fold)
except Exception as e:
print(e)
def get_folders(folder, folders):
'''Get all the subfolders '''
for i in os.listdir(folder):
new = folder + '/' + i
if os.path.isdir(new):
get_folders(new, folders)
folders.append(new)
def possible_copy_folders(folder):
folders = []
possible = {}
top_dir = os.path.dirname(folder)
get_folders(folder, folders)
folders = sorted(folders)
cur = 0
for i in range(1, len(folders)):
if folders[cur] in folders[i]:
if possible.get(folders[cur]):
possible[folders[cur]].append(folders[i])
else:
possible[folders[cur]] = [folders[i]]
else:
cur = i
# print(possible)
return possible
def confirm_copy_folders(folder):
folders = possible_copy_folders(folder) # dict
confirm = {}
for key, values in folders.items():
re_ptrn = re.compile(rf'^({key}(\s\(\d\))+)$')
for value in values:
try:
if re_ptrn.findall(value)[0][0] == value:
if confirm.get(key):
confirm[key].append(value)
else:
confirm[key] = [value]
except IndexError as e:
pass
return confirm
def dup_folder(folder):
for key, items in confirm_copy_folders(folder).items():
merge_items_and_delete(key, items)
def remove(fold):
global files
dup_folder(fold)
getFiles(fold)
files.sort(key=lambda x: len(x))
for i in permutations(files, 2):
out = isDup(*i)
if out:
print('removing ', i[1])
os.system('rm -rf "' + i[1] + '"')
files = []