-
Notifications
You must be signed in to change notification settings - Fork 4
/
goto-tool
executable file
·519 lines (371 loc) · 13.1 KB
/
goto-tool
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import re
import time
import fcntl
VERSION='3.3.1'
try:
from xdg.BaseDirectory import xdg_config_home
except ImportError:
xdg_config_home = os.path.expanduser('~/.config')
""" lockfile that is initialized in acquire_lock() but needs to be global
so that the GC does not clean this up and close the file prematurely.
If that would happen, the lock would be released too soon.
"""
lockfile = None
""" Current fields are:
key, path, access date, access count
Therefore the elements are:
path, access date, access count
"""
FIELD_SEPARATOR = ':'
ELEMENTS_PER_ROW = 3 # Attributes per row (everything but the name)
(F_PATH, F_ACCESS_TIME, F_ACCESS_COUNT) = range(ELEMENTS_PER_ROW)
# Deprecated import
import sqlite3
class deprecated(object):
""" Deprecated methods for migration from goto's temporary
sqlite3 DB to the original file format.
"""
@classmethod
def goto_needs_migration(cls):
return (os.path.exists(deprecated.goto_database_path()) and
os.path.getsize(deprecated.goto_database_path()) != 0)
@classmethod
def migrate_to_file(cls):
print("Migrating your previous SQLite3 database to file format.", file=sys.stderr)
data = deprecated.read_goto_database()
DB_F_PATH = 'path'
DB_F_NAME = 'name'
DB_F_ACCESS_TIME = 'last_access'
DB_F_ACCESS_COUNT = 'usage_count'
migrated = dict()
for (key, row) in data.items():
migrated[key] = [''] * ELEMENTS_PER_ROW
migrated[key][F_PATH] = unicode(row[DB_F_PATH])
migrated[key][F_ACCESS_TIME] = unicode(row[DB_F_ACCESS_TIME])
migrated[key][F_ACCESS_COUNT] = unicode(row[DB_F_ACCESS_COUNT])
if deprecated.goto_dirs_need_number_cleanup(migrated):
migrated = deprecated.goto_dirs_number_cleanup(migrated)
write_goto_file(migrated)
os.unlink(deprecated.goto_database_path())
print("Migration completed successfully.", file=sys.stderr)
@classmethod
def goto_database_path(cls):
try:
return os.path.abspath(os.environ['GOTO_DATABASE'])
except KeyError:
return os.path.join(xdg_config_home, 'goto_tool.sqlite3')
@classmethod
def open_database(cls):
if not os.path.exists(os.path.dirname(deprecated.goto_database_path())):
os.makedirs(os.path.dirname(deprecated.goto_database_path()))
con = sqlite3.connect(deprecated.goto_database_path())
con.row_factory = sqlite3.Row
return con
@classmethod
def read_goto_database(cls):
""" Return stored directories as dictionary. The key is the name of the
entry, the value is a dict of properties.
Example:
{'ex1':{'name': 'ex1', 'path':'/home/me/ex1', 'last_access': 11223344, 'usage_count': 10}}
"""
con = deprecated.open_database()
cur = con.cursor()
res = cur.execute("SELECT COUNT(*) FROM sqlite_master WHERE name='goto' AND type='table'")
count = res.fetchone()[0]
if count == 0 or os.path.getsize(deprecated.goto_database_path()) == 0:
deprecated.init_database(con)
return {}
res = cur.execute("SELECT * FROM goto")
rows = res.fetchall()
con.close()
return dict([ (r['name'], r) for r in rows ])
@classmethod
def goto_dirs_need_number_cleanup(cls, dirs):
""" The directory tuples were not initialized properly and the
fields for access time and access count may have missing, weird
and wrong values. Detect if this is the case.
"""
for _, t in dirs.items():
try:
int(t[F_ACCESS_COUNT])
float(t[F_ACCESS_TIME])
except ValueError:
return True
return False
@classmethod
def goto_dirs_number_cleanup(cls, dirs):
""" Apply what is described in goto_dirs_need_number_cleanup. """
fixed = list(dirs.items())
for i, t in enumerate(dirs.items()):
modified = False
try:
int(t[1][F_ACCESS_COUNT])
except ValueError:
fixed[i][1][F_ACCESS_COUNT] = 0
modified = True
try:
float(t[1][F_ACCESS_TIME])
except ValueError:
# Use the timestamp when the 'use' parameter was introduced
# to goget/goto. The shortcut was obviously not used since then.
fixed[i][1][F_ACCESS_TIME] = 1329088549.0
modified = True
if modified:
print("Cleaning entry '{}'".format(t[0]), file=sys.stderr)
return dict(fixed)
@classmethod
def fill_list(cls, l, count):
""" Return a list with contents from `l` that has at least `count`
string elements.
"""
if len(l) >= count:
return l
diff = count - len(l)
return l ([''] * diff)
@classmethod
def read_goto_file(cls):
path = goto_file_path()
# Acquire goto file lock
acquire_lock(path)
if deprecated.goto_needs_migration():
deprecated.migrate_to_file()
try:
os.stat(path)
except OSError:
return {}
def smap(x):
y = list(map(lambda e: e.strip(), x))
return y[0], deprecated.fill_list(y[1:], ELEMENTS_PER_ROW)
try:
tuples = (smap(escape_split(n, FIELD_SEPARATOR, ELEMENTS_PER_ROW)) for n in open(path, 'r').readlines())
except IOError as e:
fatal("Something went wrong while opening the file '%s': %s" % (e, path))
dirs = dict(tuples)
return dirs
@classmethod
def goto_file_number_cleanup_if_necessary(cls):
""" Read the file using the deprecated, permissive read method
and check if that file has wrong data in count and access time
fields. These are then repaired and the file is written.
"""
dirs = deprecated.read_goto_file()
if deprecated.goto_dirs_need_number_cleanup(dirs):
print("Your goto file needs some cleaning. Cleaning up.", file=sys.stderr)
dirs = deprecated.goto_dirs_number_cleanup(dirs)
print("Cleaning done.", file=sys.stderr)
write_goto_file(dirs)
def goto_file_path():
try:
return os.path.abspath(os.environ['GOTO_FILE'])
except KeyError:
return os.path.join(xdg_config_home, 'goto_favourites.list')
def escape_split(what, sep, splits):
return re.split(r"(?<!\\)" sep, what, splits)
def vmap(lineno, raw_tuple):
""" Map values from the raw_tuple to their respective type
and makes sure that each tuple is in the correct format.
At the moment syntax errors are considered fatal.
"""
stripped = list(map(lambda e: e.strip(), raw_tuple))
# Number of properties name
if len(raw_tuple) != ELEMENTS_PER_ROW 1:
fatal("Syntax error on line {0}: {1} elements detected.".format(lineno, len(raw_tuple)))
data = [''] * ELEMENTS_PER_ROW
data[F_PATH] = stripped[1 F_PATH]
try:
data[F_ACCESS_TIME] = float(stripped[1 F_ACCESS_TIME])
except ValueError:
fatal("Access time of entry on line {0} could not be read.".format(lineno))
try:
data[F_ACCESS_COUNT] = int(stripped[1 F_ACCESS_COUNT])
except ValueError:
fatal("Access count of entry on line {0} could not be read.".format(lineno))
return stripped[0], data
def rvmap(props):
""" Do the reverse of `vmap` by converting the respective properties from
their types to a string. This enables us to find programming errors
faster and prevents implicit conversion errors.
"""
# props[F_PATH] does not need to be converted.
if type(F_ACCESS_COUNT) != int:
fatal("Programming error: Non-integer access count detected.")
if type(F_ACCESS_TIME) != float and type(F_ACCESS_TIME) != int:
fatal("Programming error: Non-float or integer access time detected.")
return [str(p) for p in props]
def acquire_lock(goto_path):
""" Lock a special lock file in the same directory as the goto file
resides in. If this file does not exist, it will be created.
The lock is never explicitly released since on process exit
the lock *SHOULD* be released by the OS (on fclose()).
"""
global lockfile # prevent lockfile from being GCed after this function
# Do nothing in case the lock is already acquired.
if lockfile:
return
lockfile_path = os.path.join(os.path.dirname(goto_path), 'goto.lock')
lockfile = open(lockfile_path, 'w')
fcntl.lockf(lockfile.fileno(), fcntl.LOCK_EX)
def read_goto_file():
""" Return stored directories as dictionary. The key is the name of the
entry, the value is a list of properties ordered like this:
path, access date, access count.
Example:
{'ex1':['/home/me/ex1','11223344','10']}
"""
path = goto_file_path()
# Acquire goto file lock
acquire_lock(path)
if deprecated.goto_needs_migration():
deprecated.migrate_to_file()
try:
os.stat(path)
except OSError:
return {}
# Attempt to do a cleanup. Will return early if nothing to cleanup.
deprecated.goto_file_number_cleanup_if_necessary()
try:
tuples = (vmap(i 1, escape_split(n, FIELD_SEPARATOR, ELEMENTS_PER_ROW))
for i, n in enumerate(open(path, 'r').readlines()))
except IOError as e:
fatal("Something went wrong while opening the file '%s': %s" % (e, path))
return dict(tuples)
def write_goto_file(dirs):
path = goto_file_path()
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
data = "\n".join(["%s: %s" % (key, FIELD_SEPARATOR.join(rvmap(props))) for (key,props) in dirs.items()])
try:
open(path, 'w').write(data)
except IOError as e:
fatal("Something went wrong while writing: %s" % (e))
def print_directory_by_name(dirname):
dirs = read_goto_file()
try:
print(dirs[dirname][F_PATH])
except KeyError:
fatal("Entry '%s' not found." % (dirname,))
def mark_entry_as_used(dirname):
dirs = read_goto_file()
if not dirname in dirs:
fatal("Entry '%s' not found." % (dirname,))
count = dirs[dirname][F_ACCESS_COUNT] 1
dirs[dirname][F_ACCESS_TIME] = time.time()
dirs[dirname][F_ACCESS_COUNT] = count
write_goto_file(dirs)
print("Entry '%s' marked as used." % (dirname,))
def lookup_entry(path):
dirs = read_goto_file()
matches = [d for (d,v) in dirs.items() if v[F_PATH] == os.path.abspath(path)]
if len(matches) == 0:
fatal("No entry for path '{}' found.".format(path))
print("Path '{}' matches the following entries:".format(path))
for match in matches:
print(match)
def resolve_softlink(path):
""" Make an attempt to get the symlink from the current dir
if wanted. If that attempt fails, just return the path.
"""
if os.path.islink(path):
return os.path.abspath(path)
if path == '.':
return os.environ['PWD']
return path
def add_directory(name, path, soft=False):
""" Don't take abspath if soft=True """
dirs = read_goto_file()
try:
os.stat(path)
except OSError:
fatal('Path is not accessible: %s' % (path,))
path = soft and resolve_softlink(path) or os.path.abspath(path)
dirs[name] = [''] * ELEMENTS_PER_ROW
dirs[name][F_PATH] = path
dirs[name][F_ACCESS_COUNT] = '0'
dirs[name][F_ACCESS_TIME] = '0'
write_goto_file(dirs)
print("Entry '%s' added, points to '%s'." % (name, path))
def rm_directory(name):
dirs = read_goto_file()
try:
del dirs[name]
except KeyError:
fatal("Entry '%s' does not exist." % (name,))
write_goto_file(dirs)
print("Entry '%s' removed." % (name,))
def mv_directory(oldName, newName):
dirs = read_goto_file()
try:
dirs[newName] = dirs[oldName]
del dirs[oldName]
except KeyError:
fatal("Entry '%s' does not exist." % (oldName,))
write_goto_file(dirs)
print("Entry '%s' was rennamed to '%s'." % (oldName, newName))
def list_directories():
dirs = read_goto_file()
print("\n".join(["%s: %s" % (key,row[F_PATH]) for (key,row) in dirs.items()]))
def quantil(lst, p, elem=lambda l,i: l[i]):
p = max(min(p, 1), 0)
pi = int(p * len(lst))
if len(lst) % 2 == 0:
return (elem(lst, pi) elem(lst, pi 1)) / 2
return elem(lst, pi)
def clean_directories(force=False):
# lowest quantil of usage counts and time
dirs = read_goto_file()
if len(dirs) == 0:
# Nothing to clean, we're done.
return
counts = sorted(dirs.items(), key=lambda e: e[1][F_ACCESS_COUNT])
dates = sorted(dirs.items(), key=lambda e: e[1][F_ACCESS_TIME])
clbound = quantil(counts, 0.25, lambda l,i: l[i][1][F_ACCESS_COUNT])
dlbound = quantil(dates, 0.25, lambda l,i: l[i][1][F_ACCESS_TIME])
unused = {name for name, props in counts if props[F_ACCESS_COUNT] <= clbound and props[F_ACCESS_TIME] <= dlbound}
if not force:
print("According to age and usage you would probably want to remove (use -f):")
print("\n".join(unused))
else:
for name in unused:
rm_directory(name)
def fatal(msg):
print(msg, file=sys.stderr)
# Use 2 instead of 1 to distingush between exceptional exit (1) and
# controlled fatal exit (2).
sys.exit(2)
def usage():
fatal("goto-tool version {1}.\nUsage: {0} [get <name> | list | add [--soft] <name> <path> | rm <name> | path | lookup <path>]".format(
sys.argv[0], VERSION))
def main():
argv = sys.argv
if len(argv) in (4,5) and argv[1] == "add":
if argv[2] == "--soft" and len(argv) == 5:
add_directory(argv[3], argv[4], soft=True)
elif argv[2] == "--soft":
usage()
else:
add_directory(argv[2], argv[3])
elif len(argv) == 3 and argv[1] == "rm":
rm_directory(argv[2])
elif len(argv) == 4 and argv[1] == "mv":
mv_directory(argv[2],argv[3])
elif len(argv) == 3 and argv[1] == "get":
print_directory_by_name(argv[2])
elif len(argv) == 3 and argv[1] == "use":
mark_entry_as_used(argv[2])
elif len(argv) == 3 and argv[1] == "lookup":
lookup_entry(argv[2])
elif len(argv) == 2 and argv[1] == "list":
list_directories()
elif len(argv) == 2 and argv[1] == "path":
print(goto_file_path())
elif len(argv) >= 2 and argv[1] == "clean":
clean_directories(argv[2:3] == ['-f'])
else:
usage()
if __name__ == "__main__":
main()
# vim: noexpandtab tabstop=4