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
|
#! /usr/bin/env python
import difflib
import json
import optparse
import shlex
import sys
VERSION = "1.0.1"
ENTRIES_FILE = "saucypy.json"
def find( key, entries ):
return difflib.get_close_matches( key, entries.keys(), cutoff = 0.3 )
def parse_args():
args = sys.argv[1:]
if not args:
args = shlex.split( sys.stdin.read() )
parser = optparse.OptionParser( usage = "!source <term> | !source --add <key> <value>" )
parser.add_option( "-a", "--add", action = "store", nargs = 2 )
parser.add_option( "-i", "--index", action = "store", type = int )
parser.add_option( "-c", "--count", action = "store_true" )
parser.add_option( "-v", "--version", action = "store_true" )
return parser.parse_args( args )
def main():
options, args = parse_args()
if options.version:
print VERSION
sys.exit( 0 )
try:
entries = json.load( open( ENTRIES_FILE ) )
except IOError:
entries = {}
if options.add:
key, value = options.add
entries[key] = value
json.dump( entries, open( ENTRIES_FILE, "w" ), indent = 4, sort_keys = True )
elif options.count:
print "Entries: {0}".format( len( entries.keys() ) )
else:
if not args:
print "Expected a search argument, got nothing."
sys.exit( 1 )
matches = find( args[0], entries )
if len( matches ) > 1:
exact_match = filter( lambda x: x == args[0], matches )
if exact_match:
print entries[exact_match[0]]
elif options.index is not None:
try:
print entries[matches[options.index]]
except IndexError:
print "Match index out of range."
sys.exit( 1 )
else:
print "Matches (use -i option to pick one) -> {0}".format( ", ".join( "{0}: {1}".format( i, m ) for i, m in enumerate( matches ) ) )
elif matches:
print entries[matches[0]]
else:
print "No match found."
if __name__ == "__main__":
main()
|