-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstfw.py
executable file
·234 lines (206 loc) · 6.86 KB
/
stfw.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env python2
# -*-coding: utf-8 -*-
from __future__ import print_function
import sys
import re
import urllib2
import zlib
import json
import subprocess, os
import argparse
import webbrowser
import HTMLParser
from sets import Set
# Consts
match_error = re.compile("^([^:]*):([^:]*):([^:]*): " +
"(warning|error|fatal error|sorry, unimplemented): (.*)$")
match_tagged_message = re.compile("^(.*) (\[[^\[\]]*\])$")
# Arguments
parser = argparse.ArgumentParser(description='StackOverflow helper.')
parser.add_argument('-v', '--verbose', dest='verbose_output',
action='store_const', const=1, default=0,
help='show verbose output')
parser.add_argument('-s', '--system-open', dest='system_open',
action='store_const', const=1, default=0,
help='use system URL open command')
parser.add_argument('-o', '--open-with', dest='open_with', action='store',
default='',
help='use custom URL open command')
args = parser.parse_args()
# Colors
C_HEADER = '\033[43m\033[30m\033[1m'
C_ERROR = '\033[31m'
C_IMPORTANT = '\033[34m'
C_COMPERROR = '\033[4m\033[31m'
C_COMPWARN = '\033[4m\033[33m'
C_ENDC = '\033[0m'
def paint(s, color):
return color + str(s) + C_ENDC
# StackExchange API
request_url = "https://api.stackexchange.com/2.1/search/advanced?order=desc" +\
"&sort=relevance&site=stackoverflow&q="
url_opener = urllib2.build_opener()
def load_stackoverflow(request):
req = request_url + (urllib2.quote(request))
try:
data = url_opener.open(req).read()
jsondata = json.loads(zlib.decompressobj(16 + zlib.MAX_WBITS).
decompress(data))
if jsondata['quota_remaining'] < 10:
print (paint('Warning:', C_IMPORTANT) + ' only ' +
jsondata['quota_remaining'] + ' requests to SO left')
return jsondata['items']
except IOError, e:
print (paint("ERROR:", C_ERROR) + " Connection failed: " + str(e))
return []
# Browser API
def open_url(links):
saveerr = os.dup(2)
os.close(2)
os.open(os.devnull, os.O_RDWR)
try:
for link in links:
print (paint("Opening: ", C_IMPORTANT) + link)
if args.open_with:
subprocess.call((args.open_with, link))
else:
if args.system_open:
if sys.platform.startswith('darwin'):
subprocess.call(('open', link))
elif os.name == 'nt':
os.startfile(link)
elif os.name == 'posix':
subprocess.call(('xdg-open', link.replace('*','\\*')))
else:
webbrowser.open(link.decode("utf-8").replace(u'’','\'').
replace(u'‘','\''), new=2)
finally:
os.dup2(saveerr, 2)
# Error menu
def display_error_menu(messages):
if len(messages.items()) == 0:
sys.exit(0)
# if len(messages.items()) == 1:
# return 1
i = 1
for message,m in messages.items():
lvlstr = m['level']
if m['level'] == 'error':
lvlstr = paint(lvlstr, C_COMPERROR) + ': '
elif m['level'] == 'warning':
lvlstr = paint(lvlstr, C_COMPWARN) + ': '
print (paint(i, C_HEADER) + ' ' + lvlstr + message)
i = i + 1
print ("==> Enter message number or q to exit" )
print ("==> --------------------")
try:
selection = raw_input('==> ')
if selection == 'q':
sys.exit(0)
num = int(selection)
except:
sys.exit(0)
if num > len(messages) or num <= 0:
sys.exit(0)
print
return num
# Link menu
def display_link_menu(m, answers):
print (paint("Request: ", C_IMPORTANT) + m['message'])
for i in range(0, 5):
if i >= len(m['codeline']):
break
print (m['filename'][i] + ':' + m['line'][i] + ':' + m['col'][i] +
' > ' + m['codeline'][i].strip())
i = i + 1
googletext = '\033[34mG\033[31mo\033[33mo\033[34mg\033[32ml\033[31me\033[0m'
print (paint(0, C_HEADER) + ' ' + googletext + ' for me')
j = 1
for answer in answers:
if j > 10:
break
print (paint(j, C_HEADER) + ' ' +
HTMLParser.HTMLParser().unescape(answer['title']))
j = j + 1
print ("==> Enter post number (ex: 1 2 4-6)")
print ("==> q to exit or b to go to previous menu")
print ("==> -------------------------------")
try:
inp = str(raw_input('==> ')).split()
if len(inp) == 0:
sys.exit(0)
if inp[0] == 'q':
sys.exit(0)
elif inp[0] == 'b':
return
except:
sys.exit(0)
link_nums = Set()
for i in inp:
i = i.split('-')
try:
if len(i) == 1:
num = int(i[0])
link_nums.add(num)
if len(i) == 2:
num1 = int(i[0])
num2 = int(i[1])
for num in range(num1, num2+1):
link_nums.add(num)
except:
pass
links = []
for num in link_nums:
if num == 0:
links.append("http://google.com/search?q=" +
urllib2.quote(m['message']))
else:
if num > 0 and num <= len(answers):
links.append(answers[num-1]['link'])
open_url(links)
# Parse stdin
messages = dict()
while 1:
try:
errorline = sys.stdin.readline()
if args.verbose_output:
print (errorline, end='')
except KeyboardInterrupt:
break
if not errorline:
break
data = match_error.search(errorline)
if data:
try:
codeline = sys.stdin.readline()
if args.verbose_output:
print (codeline, end='')
except KeyboardInterrupt:
break
filename = data.group(1)
line = data.group(2)
col = data.group(3)
level = data.group(4)
data2 = match_tagged_message.search(data.group(5))
if (data2):
message = data2.group(1)
tag = data2.group(2)
else:
message = data.group(5)
tag = ""
if message not in messages:
messages.update({message:{"codeline":[], "filename":[], "line":[],
"col":[], "level":level, "message":message,
"tag":tag}})
messages[message]["codeline"].append(codeline)
messages[message]["filename"].append(filename)
messages[message]["line"].append(line)
messages[message]["col"].append(col)
if args.verbose_output:
print
sys.stdin = open('/dev/tty')
while True:
num = display_error_menu(messages)
message = messages[messages.keys()[num-1]]
answers = load_stackoverflow(message['message'])
display_link_menu(message, answers)