forked from Py-Contributors/awesomeScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
352 lines (269 loc) · 8.01 KB
/
Copy pathutils.py
File metadata and controls
352 lines (269 loc) · 8.01 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""This script has a bunch of utility functions.
All commands are issued from stdin, however, this behaves a lot like
a command line script. If any argument needs multiple words, enclose
them in double-quotes `"`
"""
import datetime
import functools
import json
import pathlib
import random
import shlex
import subprocess
import time
from typing import Callable, Mapping, TypeVar
import dateparser
import humanize
import pyperclip
from fuzzywuzzy import fuzz, process
directory = pathlib.Path(__file__).parent
json_file = directory / 'info.json'
ding = directory / 'ding.mp3'
RT = TypeVar('RT')
def read(function: Callable[..., RT]) -> Callable[..., RT]:
"""Take in a function, open the json file and pass in its data to
the function.
Parameters
----------
function : Callable
Should have a positional argument at the start to which the
data will be passed
Returns
-------
Callable
The wrapper function which does the execution
"""
@functools.wraps(function)
def reader(*args) -> RT:
with open(json_file) as f:
data = json.load(f)
return function(data, *args)
return reader
def write(function: Callable[..., Mapping[str, str]]) -> Callable[..., None]:
"""Take in a function, store it's result and write it to the JSON
Parameters
----------
function : Callable
Should return a valid dictionary which can be written to the
JSON file
Returns
-------
Callable
The wrapper function which does the execution
"""
@functools.wraps(function)
def writer(*args) -> None:
data = function(*args)
with open(json_file, 'w') as wf:
json.dump(data, wf, indent=2)
return writer
def copy_to_clipboard(function: Callable[..., str]) -> Callable[..., None]:
"""Take in a function, store its result, copy it to the clipboard
and display it.
Parameters
----------
function : Callable
The function should return the string which is to be copied
to the clipboard.
Returns
-------
Callable
The wrapper function which does the execution.
"""
@functools.wraps(function)
def copy(*args) -> None:
result = function(*args)
pyperclip.copy(result)
if len(result) > 40:
result = f'{result[:40]}...'
print(f'Current clipboard: {result}')
return copy
@copy_to_clipboard
def random_case(message: str) -> str:
"""Convert the string to RanDoM CasE.
Parameters
----------
message : str
The string to be converted
Returns
-------
str
The string in RandOm caSe
"""
characters = []
for character in message:
converted_char = random.choice([character.upper(), character.lower()])
characters.append(converted_char)
return ''.join(characters)
@write
@read
def add(data: dict[str, str], key_word: str, info: str) -> dict[str, str]:
"""Add provided key and value to the JSON file.
Parameters
----------
data : dict of str, str
Internally used by `read` to pass in the current data
key_word : str
The key to be used
info : str
The value to be stored in the key
Returns
-------
dict of str, str
Internally used by the `write` decorator to update the current
data.
Raises
------
Exception
When the user doesn't want to override the value stored in the
`keyword` when it already exists.
"""
if key_word in data:
message = (f'Are you sure you want to override {key_word} '
f'having value: {data[key_word]}?\t')
if input(message) not in ('yes', 'y'):
raise Exception('Exited')
data[key_word] = info
return data
@write
@read
def remove(data: dict[str, str], key_word: str) -> dict[str, str]:
"""Remove `key_word` from the JSON file.
Parameters
----------
data : dict of str, str
Internally passed in by `read` to provide the current data
in the file
key_word : str
The key to be removed
Returns
-------
dict of str, str
The updated data with the key removed
Raises
------
Exception
When the user doesn't want to remove the recommended
fuzzy-matched string incase `key_word` doesn't already
exist
"""
key = key_word
try:
data[key_word]
except KeyError:
closest_match = process.extractOne(key_word, list(data),
scorer=fuzz.ratio)[0]
if (input(f'Do you want to remove {closest_match} instead?\t')
in ('yes', 'y')):
key = closest_match
else:
raise Exception('Exited')
del data[key]
return data
@read
def list_data(data: dict[str, str]) -> None:
"""Print the current data in the JSON file in a pretty format.
Parameters
----------
data : dict of str, str
Internally passed in by `read` to provide the current data
in the file
"""
try:
align = max(len(key) for key in data)
except ValueError:
print('No data added in yet')
return
for key, value in data.items():
if len(value) > 40:
value = f'{value[:40]}...'
print(f'{key:{align}} - {value}')
@copy_to_clipboard
@read
def clipboard(data: dict[str, str], key_phrase: str) -> str:
"""Copy the value stored in the passed in key
Parameters
----------
data : dict of str, str
Internally passed in by `read` to provide the current data
in the file
key_phrase : str
The key to copy the value of
Returns
-------
str
The value in the key
"""
best_search = process.extractOne(key_phrase, list(data),
scorer=fuzz.ratio)[0]
return data[best_search]
def diceroll(num_faces: str = "6") -> None:
"""Roll a dice and print the result
Parameters
----------
num_faces : str, optional
The faces of the die, by default 6
"""
print(random.randint(1, int(num_faces)))
def timer(sleep_for: str) -> None:
"""A snazzy timer
It prints the time left into the console, and plays a sound when
completed.
Parameters
----------
sleep_for : str
The duration the timer to run for, in any valid format.
The format could be a human readable one or a stricter
one.
Raises
------
ValueError
If the format provided is invalid or the sleep duration
is negative
"""
current = datetime.datetime.now()
sleep_date = dateparser.parse(sleep_for, languages=['en'])
if sleep_date is None:
raise ValueError('Time not recognised')
sleep_seconds = round((current - sleep_date).total_seconds())
if sleep_seconds < 0:
raise ValueError("sleep period must be positive")
while sleep_seconds:
print('\r' + ' ' * 100, end='\r\t')
print(humanize.naturaltime(sleep_seconds, future=True), end='\r')
time.sleep(1)
sleep_seconds -= 1
else:
print()
subprocess.run(['open', ding])
methods = {function: function.__name__ for function in [
random_case, add, remove, list_data, clipboard, diceroll, timer
]}
print('Available functionalities:')
for item, function in enumerate(methods.values(), start=1):
print(f'{item}. {function}')
else:
print()
while True:
command = input()
if command.lower() == 'quit':
break
try:
choice, *args = shlex.split(command)
except ValueError:
continue
args = [arg if arg != '-p'
else pyperclip.paste() for arg in args]
try:
function = process.extractOne(choice, methods,
scorer=fuzz.ratio, score_cutoff=60)[2]
except TypeError:
print('Enter a valid function')
continue
try:
function(*args)
except Exception as e:
print('Function errored out')
print(e)
finally:
print()