-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslinker_v3.0.py
executable file
·189 lines (171 loc) · 7.11 KB
/
slinker_v3.0.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#!/usr/local/bin/python3.11
import pathlib
import os
import sys
import subprocess
import humanize as hm
import datetime as dt
from collections import Counter
from prettytable import PrettyTable
#############################################################################################################
# Global variables
#############################################################################################################
SCRIPT_NAME = os.path.basename(__file__)
START_TIME = dt.datetime.now()
TORBASE = os.getenv('TORBASE')
LOCATIONS_FILE = os.path.join(TORBASE, 'Folder_Locations_v4.csv')
SYMLINK_BASE = os.path.join(TORBASE, 'zzzNew/')
# MARKER_CHAR = '#'
SPACER = ' '
SEARCH_PARAM_TROW_DIVIDER = f'+{"-" * 18}+{"-" * 59}+'
SYMLINK_TROW_DIVIDER = f'+{"-" * 79}+{"-" * 14}+'
#############################################################################################################
# End Globals
#############################################################################################################
#############################################################################################################
def item_search(string):
results_list = []
grep_cmd = f'grep -i "{string}" {LOCATIONS_FILE} | cut -d$\'\t\' -f2'
try:
grep_result = subprocess.run(
grep_cmd,
shell=True,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).stdout.decode('utf-8').split('\n')
except subprocess.CalledProcessError as e: # Handle the error if grep returns a non-zero exit status
if e.returncode == 1: # No matches found
return 0
else: # Other errors (e.g., file not found, permission denied, etc.)
return str(e.stderr.decode('utf-8'))
# Search returned a non-error value, so proceeding
if not grep_result: # Nothing found
return 0
else: # Found item in index
for result in grep_result:
r = result.strip()
if not r: # After stripping leading and trailing whitespace, there was nothing left
continue
else:
results_list.append(r)
if not results_list:
return 0
else:
print(f'Function "item_search" returns a list of {type(results_list[0])}')
return results_list
#############################################################################################################
#############################################################################################################
def create_symlink(item_path):
symlink_cmd = f'ln -s "{item_path}" {SYMLINK_BASE}'
try:
subprocess.run(
symlink_cmd,
shell=True,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).stdout.decode('utf-8')
return 1
except subprocess.CalledProcessError as e:
return str(e)
#############################################################################################################
#############################################################################################################
def main():
# SEARCH_PARAM_TROW_DIVIDER = f'+{"-" * 18}+{"-" * 59}+'
# SYMLINK_TROW_DIVIDER = f'+{"-" * 79}+{"-" * 14}+'
print(f'\n{"#" * 100}')
print(f'Starting execution of {SCRIPT_NAME}\n')
if not len(sys.argv) >= 2:
print(f'Execution requires search parameter, but none detected. Try again.....')
print('{:<70} {:>20}'.format('Total runtime:', hm.precisedelta(dt.datetime.now() - START_TIME)))
print(f'{"#" * 100}\n\n')
quit(0)
# Create de-duped list from passed parameters
param_list = list(dict.fromkeys(sys.argv[1:]))
param_count = len(param_list)
# Search Index for each passed parameter
print(f'+{"-" * 78}+')
print(f'| {"Search Parameters":^76} |')
print(SEARCH_PARAM_TROW_DIVIDER)
print('| {:^16} | {:^57} |'.format("Index:", LOCATIONS_FILE))
print('| {:^16} | {:^57} |'.format("Search Items:", param_count))
print(f'+{"-" * 18}+{"-" * 59}+')
param_dict = {}
counter = 1
for param in param_list:
# print('| {:^16} | {:^57} |'.format("Result:", param_dict['string']))
print('| {:^16} | {:^57} |'.format(f'Item {counter}:', param_dict['string']))
result = item_search(param)
if not isinstance(result, list):
param_dict[param] = {
'type': 'list',
'string': 'NOT FOUND!!!'
}
else:
param_dict[param] = {
'type': 'list',
'string': 'SUCCESS!!!'
}
# elif isinstance(result, int):
# param_dict[param] = {
# 'type': 'int',
# 'string': 'NOT FOUND!!!'
# }
# else:
# param_dict[param] = {
# 'type': 'string',
# 'string': f'ERROR!!!\n{result}'
# }
# print(param_dict)
print('| {:^16} | {:^57} |'.format("Search Result:", param_dict['string']))
counter += 1
'''
for item in param_list:
k, v = item.split(',')
'''
'''
for item in param_list:
item_lookup = item_search(item)
if isinstance(item_lookup, list):
print('{:^80} \t{:^15}'.format('Name ', 'Result'))
print(f'+{dash * 79}+{dash * 14}+
print(('| '))
'''
# type_counts = Counter(item['type'] for item in param_dict.values())
'''
for item in param_list:
param_table = PrettyTable()
param_table.field_names = ['Search Parameters', '']
param_table.add_row(['Index:', LOCATIONS_FILE])
param_table.add_row(['Param count:', len(param_list)])
param_table.add_row(['String:', item])
item_lookup = item_search(item)
if isinstance(item_lookup, list):
param_table.add_row(['Result:', 'SUCCESS!!'])
param_table.add_row(['Results count:', len(item_lookup)])
print('{:^80} \t{:^15}'.format('Name ', 'Result'))
for i in item_lookup:
result_table = PrettyTable()
result_table.fieldnames = ['Name', 'Result']
v = i.split(',')[-1]
val = pathlib.PurePosixPath(v).name
symlink_result = create_symlink(v)
if isinstance(symlink_result, int):
result_table.add_row([val, 'SUCCESS!!'])
else:
result_table.add_row([val, '__FAILED__'])
if isinstance(item_lookup, int):
param_table.add_row(['Result:', 'NOT FOUND!!!'])
if isinstance(item_lookup, str):
param_table.add_row(['Result:', 'ERROR!!!' + f'\n{item_lookup}'])
print(param_table)
print(f'\nCreating symlinks for each result:')
result_table.align["Name"] = "l"
print(result_table)
'''
print('{:<71} {:>20}'.format('Execution complete. Total runtime:', hm.precisedelta(dt.datetime.now() - START_TIME)))
print(f'{"#" * 100}\n\n')
#############################################################################################################
if __name__ == "__main__":
main()