This repository has been archived by the owner on Jan 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pydocs.py
214 lines (185 loc) · 7.3 KB
/
pydocs.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
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
#!/usr/bin/env python
# encoding: utf-8
import alfred # https://github.com/nikipore/alfred-python
import cPickle
import difflib
import HTMLParser
import os
import sys
import re
import subprocess as sp
import urllib2
_URL = 'http://docs.python.org'
def has_internet():
try:
urllib2.urlopen('http://google.com', timeout=2)
return True
except (urllib2.HTTPError, urllib2.URLError):
return False
def get_index(v='2'):
# local storage
pkl = os.path.join(alfred.work(volatile=False), 'index%s.pkl' % v)
# fetch if non existing locally
fetch(pkl)
return cPickle.load(open(pkl))
def clean_index(v='2'):
# local storage
pkl = os.path.join(alfred.work(volatile=False), 'index%s.pkl' % v)
tmp = pkl + '.tmp'
if fetch(tmp):
os.rename(tmp, pkl)
return True
else:
return False
def clean_HTML(parser, s):
return parser.unescape(re.sub('<.*?>', '', s))
def fetch(pkl):
if not os.path.exists(pkl):
if has_internet():
v = pkl.split('.pkl')[0][-1]
data = urllib2.urlopen(_URL + '/%s/searchindex.js' % v).read()
index = {}
for d in re.findall('[\"\.\w]*:{[^{}]*}', data):
tmpdict = re.sub('(?<![\"\w])([\.\w]{1,}):', r'"\1":',
d.replace('""', '"all"'))
index.update(eval('{' + tmpdict + '}'))
for n in ['filenames', 'titles']:
tmplist = re.search(',%s:(\[.*?\])' % n, data).group(1)
index.update({n: eval(tmplist)})
objtypes = index.pop('objtypes')
objnames = index.pop('objnames')
titles = index.pop('titles')
fnames = index.pop('filenames')
cPickle.dump([index, objtypes, objnames, titles, fnames],
open(pkl, 'wb'), protocol=-1)
return True
else:
return False
else:
return True
def search(query, v='2', cutoff=0.7):
index, objtypes, objnames, titles, fnames = get_index(v)
# fetch function directly when giving package
if '.' in query.strip('.'):
tmpquery = query
while '.' in tmpquery:
tmpquery = '.'.join(tmpquery.split('.')[:-1])
if tmpquery in index:
# fake index
index = {tmpquery: index[tmpquery]}
tmpquery = query.replace(tmpquery + '.', '')
break
else:
tmpquery = query
order = []
# list package directly
if query.endswith('.') and query.rstrip('.') in index:
q = query.rstrip('.')
matches = {q: sorted(index[q].keys())}
# search for similar entries
else:
matches = {}
# match in all keys
allkeys = [[i, j.keys()] for i, j in index.iteritems()]
for k in allkeys:
# only first match
d = difflib.get_close_matches(tmpquery, k[1], 1, cutoff=cutoff)
if d:
matches.update({k[0]: [d[0]]})
# + startswith list
if '.' in query.strip():
s = sorted([i for i in k[1]
if i.lower().startswith(tmpquery.lower())
and i not in d])
matches.setdefault(k[0], []).extend(s)
# order by closest global match
order = difflib.get_close_matches(tmpquery,
reduce(list.__add__,
matches.values()),
100, cutoff)
outmatch = []
html = HTMLParser.HTMLParser()
terms = matches.pop('terms', [''])[0]
# global ordering, with modules and functions first
for m1, m2 in sorted(matches.items(),
key=lambda m: (m[0] != 'all') + order.index(m[1][0])
if m[1][0] in order else 100):
for m in m2:
i = index[m1][m]
tag = '%s%s' % ((m1 + '.') if m1 != 'all' else '', m)
url = _URL + '/%s/%s.html?highlight=%s#%s' % (v, fnames[i[0]],
query, tag)
outmatch.append([url,
u'%s — %s' % (tag, objnames[str(i[1])]),
clean_HTML(html, titles[i[0]])])
if terms:
m = terms
terms = index['terms'][m]
if not isinstance(terms, (list, tuple)):
terms = [terms]
outterm = []
for t in terms:
url = _URL + '/%s/%s.html?highlight=%s' % (v, fnames[t], m)
outterm.append([url, clean_HTML(html, titles[t]), m])
outmatch.extend(sorted(outterm, key=lambda x: x[1]))
return outmatch
if __name__ == '__main__':
args = alfred.args()
# clean
if len(args) == 1:
# get python version from URL
v = re.search('docs.python.org/(\d)/.*', args[0]).group(1)
if clean_index(v):
print 'Index rebuilt!'
else:
print 'No internet connexion found, index not rebuilt.'
else:
v, query = args
results = []
# define a function using the local pydoc
define = os.path.exists('define.txt')
if define:
d = open('define.txt').read().strip()
os.remove('define.txt')
out = re.split('\n',
sp.Popen('/usr/bin/pydoc %s' % d, shell=True,
stdout=sp.PIPE).stdout.read().strip())
if re.search('^Help on[\s\-\w]* function', out[0]) is None:
results.append(alfred.Item(attributes={'valid': False},
title='Not a function!', subtitle='',
icon='icon.png'))
define = False
else:
out = out[2:]
title = re.sub('^[\.\w]* = ', '', out.pop(0))
if out and re.findall('(\w*\()', title)[0] in out[0]:
title += u' → ' + out.pop(0).strip()
subtitle = []
if out:
while not re.sub('^\s*', '', out[0]):
out.pop(0)
l = re.sub('^\s*', '', out.pop(0))
while l:
subtitle.append(l)
l = re.sub('^\s*', '', out.pop(0)) if out else ''
results.append(alfred.Item(attributes={'valid': False},
title=title,
subtitle=' '.join(subtitle),
icon='icon.png'))
query = d
# search for documentation entries
if query:
for s in search(query, v):
# do not define similar entries
if define and len(results) == 2:
break
autocomplete = re.sub('^[\d\.]*\s*', '', s[1].split(u'—')[0])
# do not use UID, to avoid learning
attr = {'arg': s[0],
'autocomplete': autocomplete.strip()}
item = alfred.Item(attributes=attr,
title=s[1] if not define else 'Go to documentation',
subtitle=s[2] if not define else '',
icon='icon.png')
results.append(item)
alfred.write(alfred.xml(results))