forked from grantjenks/python-diskcache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
465 lines (389 loc) · 14.9 KB
/
Copy pathcli.py
File metadata and controls
465 lines (389 loc) · 14.9 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
"""Command line interface to disk cache."""
import argparse
import functools
import os
import sys
import pickle
import time
from diskcache import __version__
from diskcache.core import Cache, Timeout
# resolve cache directory
def resolve_directory(args):
"""Determines which cache directory to use.\n
Precedence order: args.directory > env variable: DISKCACHE_DIRECTORY > default: './cache'
"""
if args.directory is not None:
return args.directory
# if args does not contain directory, check env variable or use default directory as './cache' in the current folder
return os.environ.get('DISKCACHE_DIRECTORY', './cache')
_MISSING = object() # sentinel for missing
def handle_timeout(action):
"""Decorator for cmd_* handlers: catch Timeout and print a consistent error message."""
def decorator(func):
@functools.wraps(func)
def wrapper(cache, args):
try:
return func(cache, args)
except Timeout:
key = getattr(args, 'key', None)
if key is not None:
print(f"Error: Timeout Error occurred while {action} the value of '{key}'")
else:
print(f"Error: Timeout Error occurred while {action}")
return 1
return wrapper
return decorator
def cmd_get(cache, args):
"""Handle the 'get' subcommand: fetch and print a value by key."""
value = cache.get(args.key, default=_MISSING) # keeping the _MISSING separate from the actual value 'None', original get method uses default=None for missing keys
if value is _MISSING:
print(f"Error: key '{args.key}' not found")
return 1
print(value)
return 0
@handle_timeout('setting')
def cmd_set(cache, args):
"""Handle the 'set' subcommand: add the {key: value} pair to the cache"""
cache.set(args.key, args.value, expire=args.expire, tag=args.tag)
return 0
@handle_timeout('adding')
def cmd_add(cache, args):
"""Handle the 'add' subcommand: add the {key: value} pair only if the key does not already exist or has expired."""
added = cache.add(args.key, args.value, expire=args.expire, tag=args.tag)
if not added:
print(f"Error: key '{args.key}' already exists")
return 1
return 0
@handle_timeout('deleting')
def cmd_delete(cache, args):
"""Handle the 'delete' subcommand: remove a key from the cache."""
deleted = cache.delete(args.key)
if not deleted:
print(f"Error: key '{args.key}' not found")
return 1
return 0
@handle_timeout('touching')
def cmd_touch(cache, args):
"""Handle the 'touch' subcommand: update the expire time"""
touched = cache.touch(args.key, expire=args.expire)
if not touched:
print(f"Error: key '{args.key}' not found or alread expired.")
return 1
if touched:
print(f"expire time updated for key: {args.key}")
return 0
@handle_timeout('popping')
def cmd_pop(cache, args):
"""Handle the 'pop' subcommand: remove corresponding item for key from the cache and returns value"""
popped = cache.pop(args.key, default=_MISSING, expire_time=args.expire_time, tag=args.tag)
value = popped[0] if args.expire_time or args.tag else popped
if value is _MISSING:
print(f"Error: key '{args.key}' not found")
return 1
if args.expire_time and args.tag:
_, expire_time, tag = popped
print(f"value: {value} - expire_time: {expire_time} - tag: {tag}")
elif args.expire_time:
_, expire_time = popped
print(f"value: {value} - expire_time: {expire_time}")
elif args.tag:
_, tag = popped
print(f"value: {value} - tag: {tag}")
else:
print(f"value: {value}")
return 0
@handle_timeout('incrementing')
def cmd_incr(cache, args):
increased = cache.incr(args.key, delta=args.delta, default=args.default)
print(increased)
return 0
@handle_timeout('decrementing')
def cmd_decr(cache, args):
decreased = cache.decr(args.key, delta=args.delta, default=args.default)
print(decreased)
return 0
@handle_timeout('checking volume')
def cmd_volume(cache, args):
"""Handle the 'volume' subcommand: prints the total on-disk size of the cache"""
total_size = cache.volume()
print(f"{total_size} bytes ({total_size / 1024:.2f} KB, {total_size / (1024 ** 2):.2f} MB)")
return 0
@handle_timeout('counting')
def cmd_count(cache, args):
"""Handle the 'count' subcommand: prints the number of items in the cache."""
count = len(cache)
print(count)
return 0
# no handle_timeout needed
def cmd_keys(cache, args):
"""Handle the 'keys' subcommand: list all the keys in the cache"""
not_found = True
for key in cache.iterkeys():
not_found = False
print(key)
if not_found:
print("No keys found")
return 1
return 0
@handle_timeout('checking stats')
def cmd_stats(cache, args):
"""Handle the 'stats' subcommand: show cache hit/miss statistics."""
hits, misses = cache.stats()
print(f"hits: {hits} misses: {misses}")
return 0
@handle_timeout('clearing')
def cmd_clear(cache, args):
"""Handle the 'clear' subcommand: clears the entire cache and returns the number of items removed."""
length = len(cache)
prompt = f"This will remove all {length} items from the cache. Do you want to continue?"
if not args.yes:
confirmation = confirm(prompt=prompt)
if not confirmation:
print("Operation Aborted!")
return 1
cleared = cache.clear()
print(f"{cleared} items cleared from the cache.")
return 0
@handle_timeout('expiring')
def cmd_expire(cache, args):
"""Handle the 'expire' subcommand: removes expired items and returns the number of items removed."""
expired = cache.expire()
print(f"{expired} expired items removed from the cache.")
return 0
@handle_timeout('culling')
def cmd_cull(cache, args):
"""Handle the 'cull' subcommand: culls items until volume is under the size limit and returns the number of items removed."""
culled = cache.cull()
print(f"{culled} items culled from the cache.")
return 0
# explicit Timeout handling needed due to different shape
def cmd_evict(cache, args):
"Handle the 'evict' subcommand: removes and returns the number of items removed with a specific tag from cache."
prompt = f"This will remove all items tagged '{args.tag}'. Do you want to continue?"
if not args.yes:
confirmation = confirm(prompt)
if not confirmation:
print("Operation Aborted!")
return 1
try:
evicted = cache.evict(args.tag)
except Timeout as e:
print(f"Error: Timeout occurred after evicting {e.args[0]} item(s) with tag '{args.tag}'")
return 1
print(f"{evicted} items evicted with tag {args.tag}")
return 0
@handle_timeout('checking')
def cmd_check(cache, args):
"""Handle the 'check' subcommand: verify database and filesystem consistency."""
if args.fix and not args.yes:
prompt = "This will resolve all the inconsistencies and warnings. Do you want to continue?"
confirmation = confirm(prompt)
if not confirmation:
print("Operation Aborted!")
return 1
checked = cache.check(fix=args.fix)
if(len(checked) == 0):
print("No warnings found. Database and filesystem are consistent.")
return 0
else:
print(f"{len(checked)} warnings found.\n")
for warning in checked:
print(warning)
return 1
def confirm(prompt):
"""Ask the user to confirm a destructive action. Returns ture only on an explicit yes."""
response = input(f"{prompt} [y/N]: ").strip().lower()
return response in ('y', 'yes')
@handle_timeout('exporting')
def cmd_export(cache, args):
"""Handle the 'export' subcommand: back up the cache contents to a portable file."""
items = []
for key in cache.iterkeys():
value, expire_time, tag = cache.get(key, expire_time=True, tag=True)
if expire_time is not None:
expire = expire_time - time.time()
else:
expire = None
items.append({
'key' : key,
'value' : value,
'expire' : expire,
'tag' : tag,
})
try:
with open(args.file, 'wb') as f:
pickle.dump(items, f)
except OSError as e:
print(f"Error: could not write to '{args.file}' : {e}")
return 1
print(f"{len(items)} item(s) exported to '{args.file}'")
return 0
def build_parser():
"""Build the top level parser and its subparser.
"""
parser = argparse.ArgumentParser(
prog="diskcache",
description="Command line interface for diskcache."
)
parser.add_argument(
'-d', '--directory',
default=None,
help='cache directory (default: $DISKCACHE_DIRECTORY or ./cache)'
)
parser.add_argument(
'-v', '--version',
action='version',
version=f" %(prog)s {__version__}"
)
subparsers = parser.add_subparsers(dest="command") # dest='command' will register the subcommand(get,set, etc.) in args.command
# subcommands parser
get_parser = subparsers.add_parser('get', help='Retrieve a value by key')
get_parser.add_argument('key', help='the key to look up')
set_parser = subparsers.add_parser('set', help='Set a value for a key')
set_parser.add_argument('key', help='the key name for key:value pair')
set_parser.add_argument('value', help='the value for the key')
# optional arguments
set_parser.add_argument(
'--expire',
type=float,
default=None,
help='seconds until the key expires (default: no expiry)'
)
set_parser.add_argument(
'--tag',
default=None,
help='tag to associate with the key'
)
add_parser = subparsers.add_parser('add', help='Add a value for a key only if it does not already exist')
add_parser.add_argument('key', help='the key name for key:value pair')
add_parser.add_argument('value', help='the value for the key')
add_parser.add_argument(
'--expire',
type=float,
default=None,
help='seconds until the key expires (default: no expiry)'
)
add_parser.add_argument(
'--tag',
default=None,
help='tag to associate with the key'
)
delete_parser = subparsers.add_parser('delete', help='Delete a key from the cache')
delete_parser.add_argument('key', help='the key to delete')
touch_parser = subparsers.add_parser('touch', help='Update the expire time of a key')
touch_parser.add_argument('key', help='the key to touch')
touch_parser.add_argument(
'--expire',
type=float,
default=None,
help='seconds until the key expires (default: no expiry)'
)
pop_parser = subparsers.add_parser('pop', help='Remove and return the value for a key')
pop_parser.add_argument('key', help='the key to pop')
pop_parser.add_argument(
'--expire-time', # hyphen b/w expire and time converts to underscore by argparse
action='store_true', # if --expire-time flag is present in command then set the flag to true
help='also print the expire time of the key'
)
pop_parser.add_argument(
'--tag',
action='store_true', # if --tag flag is present in the command then set the flag to true
help='also print the tag of the key'
)
incr_parser = subparsers.add_parser('incr', help='Increment the value of a key')
incr_parser.add_argument('key', help='the key to increment')
incr_parser.add_argument(
'--delta',
type=int,
default=1,
help='amount to increment by (default: 1)'
)
incr_parser.add_argument(
'--default',
type=int,
default=0,
help='value to use if the key is missing (default: 0)'
)
decr_parser = subparsers.add_parser('decr', help='Decrement the value of a key')
decr_parser.add_argument('key', help='the key to decrement')
decr_parser.add_argument(
'--delta',
type=int,
default=1,
help='amount to decrement by (default: 1)'
)
decr_parser.add_argument(
'--default',
type=int,
default=0,
help='value to use if the key is missing (default: 0)'
)
volume_parser = subparsers.add_parser('volume', help='Print the total size of the cache on disk')
count_parser = subparsers.add_parser('count', help='Print the number of items in the cache')
keys_parser = subparsers.add_parser('keys', help='Print all the keys in the cache')
stats_parser = subparsers.add_parser('stats', help='Show cache hit/miss statistics')
expire_parser = subparsers.add_parser('expire', help='Remove expired items from the cache')
cull_parser = subparsers.add_parser('cull', help='Cull items from the cache until volume is under the size limit')
clear_parser = subparsers.add_parser('clear', help='Remove all items from the cache')
clear_parser.add_argument(
'-y', '--yes',
action='store_true',
help='skip confirmation prompt'
)
evict_parser = subparsers.add_parser('evict', help='Remove items with a matching tag from the cache')
evict_parser.add_argument('tag', help='the tag identifying items to evict')
evict_parser.add_argument(
'-y', '--yes',
action='store_true',
help='skip confirmation prompt'
)
check_parser = subparsers.add_parser('check', help='Verify database and filesystem consistency')
check_parser.add_argument(
'--fix',
action='store_true',
help='fix the inconsistencies found during checking'
)
check_parser.add_argument(
'-y', '--yes',
action='store_true',
help='skip confirmation prompt'
)
export_parser = subparsers.add_parser('export', help='Export the cache data to a portable file')
export_parser.add_argument('file', help='File path to which data to be exported')
return parser, subparsers
def main(argv=None):
"""Entry point. argv=None lets the argparse read the sys.argv.\n
Passing a list explicitly will enable testing.
"""
parser, _ = build_parser()
args = parser.parse_args(argv)
directory = resolve_directory(args)
if not args.command:
parser.print_help()
return 1
cache = Cache(directory)
# commands dispatch
commands = {
'get' : cmd_get,
'set' : cmd_set,
'add' : cmd_add,
'delete' : cmd_delete,
'touch' : cmd_touch,
'pop' : cmd_pop,
'incr' : cmd_incr,
'decr' : cmd_decr,
'volume' : cmd_volume,
'count' : cmd_count,
'keys' : cmd_keys,
'stats' : cmd_stats,
'expire' : cmd_expire,
'cull' : cmd_cull,
'clear' : cmd_clear,
'evict' : cmd_evict,
'check' : cmd_check,
'export' : cmd_export,
}
handler = commands[args.command]
return handler(cache, args)
if __name__ == '__main__':
sys.exit(main())