-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMeteorReval.py
executable file
·338 lines (281 loc) · 10.9 KB
/
MeteorReval.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
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
import sublime
import functools
import sublime_plugin
import urllib.request
import re
PROJECT_NAME = 'meteor_reval'
settings = None
RUN_COMMAND = PROJECT_NAME
PROJECT_SETTINGS_KEY = PROJECT_NAME
def plugin_loaded():
global settings
settings = sublime.load_settings("MeteorReval.sublime-settings")
""" Pattern taken from
<https://github.com/jonlabelle/SublimeJsPrettier/blob/8d731207666f003ca31ec3646c9ce3373c214105/JsPrettier.py>
"""
def get_project_setting(key):
project_settings = sublime.active_window().active_view().settings()
if not project_settings:
return None
project_setting = project_settings.get(PROJECT_SETTINGS_KEY)
if project_setting:
if key in project_setting:
return project_setting[key]
return None
def get_setting(key, default_value=None):
value = settings.get(key, default_value)
project_value = get_project_setting(key)
if project_value is None:
return value
return project_value
class meteorReval(sublime_plugin.EventListener):
pending = 0
def handle_timeout(self, view):
self.pending = self.pending - 1
if self.pending == 0:
view.run_command(RUN_COMMAND)
def on_modified_async(self, view):
if get_setting('reload_on_modified') is True:
required_path = get_setting('required_path')
required_regex = get_setting('required_regex')
file_path = view.file_name()
if (file_path and file_path.find(required_path) >= 0 and re.search(required_regex, file_path)):
self.pending = self.pending + 1
sublime.set_timeout(functools.partial(self.handle_timeout, view), get_setting('reload_debounce'))
class meteorRevalCommand(sublime_plugin.TextCommand):
def run(self, view):
if (self.view.file_name()):
path = get_setting('path')
pathStartRegEx = get_setting('path_start_regex')
hostname = get_setting('hostname')
port = get_setting('port')
endpoint = get_setting('endpoint')
fileName = self.view.file_name().replace(path, '')
fileName = re.sub(pathStartRegEx, '', fileName)
url = 'http://' + hostname + ':' + str(port) + endpoint + '?filePath=' + fileName
print (url)
data = self.view.substr(sublime.Region(0, self.view.size()))
request = HttpAsyncRequest(url)
request.set_content(str.encode(data))
request.set_header('Content-type', 'text/plain')
request.send()
# Library for doing async HTTP (threading yeah!)
_user_agent = "qualia"
import threading as _threading
_is_old = 3 / 2 == 1 # Yeah, I'm sure there's a better way. Deal with it.
if _is_old:
import urllib as _urllib
import urllib2 as _urllib2
import urlparse as _urlparse
else:
import urllib as _urllib
import urllib.parse as _urllib_parse
import urllib.request as _urllib_request
def _parse_url(url):
return _urlparse.urlparse(url)
def set_user_agent(value):
global _user_agent
_user_agent = value
def decode_url_value(value):
if _is_old:
return _urllib.unquote(value).decode('utf8')
else:
return _urllib_parse.unquote(value)
def encode_url_value(value):
if _is_old:
return _urllib2.quote(value.encode('utf8'))
else:
return _urllib_parse.quote(value)
def _send_impl(req_obj, method, url, headers, content):
if _is_old:
opener = _urllib2.build_opener(_urllib2.HTTPHandler)
if content == None:
request = _urllib2.Request(url)
else:
request = _urllib2.Request(url, data=content)
else:
opener = _urllib_request.build_opener(_urllib_request.HTTPHandler)
if content == None:
request = _urllib_request.Request(url)
else:
request = _urllib_request.Request(url, data=content)
for header in headers:
request.add_header(header[0], header[1])
request.get_method = lambda:method
output = opener.open(request)
content = output.read()
headers = {}
for header_key in output.headers.keys():
headers[header_key] = output.headers[header_key]
response_message = output.msg
response_code = output.code
req_obj._set_result(response_code, response_message, content, headers)
class HttpAsyncRequest:
def __init__(self, url):
bad_format = False
try:
if _is_old:
url_parts = _parse_url(url)
else:
url_parts = _urllib_parse.urlparse(url)
if url_parts.scheme == '' or url_parts.netloc == '':
bad_format = True
except:
bad_format = True
if bad_format:
raise Exception("Bad URL! Bad!")
self.mutex = _threading.Lock()
self.method = 'GET'
self.scheme = url_parts.scheme
self.host = url_parts.hostname
self.port = url_parts.port
self.path = url_parts.path
self.fragment = url_parts.fragment
self.params = url_parts.params
self.original_query = url_parts.query # use this if query params are not modified
self.query = None # if modified, clear original_query and populate this with a dictionary lookup
self.header_formatting = {} # preserves the formatting of the header key
self.header_values = {} # canonical key of header with list of values of that header
self.content = None
self.set_header('User-Agent', _user_agent)
self.done = False
self.response_code = -1
self.response_message = None
self.response_content = None
self.response_headers_values = None
self.response_headers_formatting = None
def send(self):
url = self.scheme + '://' + self.host
if self.port != None:
url += ':' + str(self.port)
if self.path != None and self.path != '':
if self.path[0] != '/':
self.path = '/' + self.path
url += self.path
if self.params != None and self.params != '':
url += ';' + self.params
if self.query == None:
if self.original_query != '':
url += '?' + self.original_query
else:
queries = []
keys = self.query.keys()[:]
keys.sort() # deterministic requests
for key in keys:
e_key = encode_url_value(key)
for value in self.query[key]:
e_value = encode_url_value(value)
queries.append(e_key + '=' + e_value)
url += '?' + '&'.join(queries)
if self.fragment != '':
url += '#' + self.fragment
headers = []
keys = list(self.header_formatting.keys())
keys.sort()
for key in keys:
f_key = self.header_formatting[key]
for value in self.header_values[key]:
headers.append((f_key, value))
thread = _threading.Thread(target = _send_impl, args = (self, self.method, url, headers, self.content))
thread.daemon = True
thread.start()
def _set_result(self, code, message, content, headers):
self.mutex.acquire()
try:
self.response_code = code
self.response_message = message
self.response_content = content
self.response_headers_values = {}
self.response_headers_formatting = {}
for key in headers.keys():
ckey = key.lower()
self.response_headers_values[ckey] = headers[key]
self.response_headers_formatting[ckey] = key
finally:
self.mutex.release()
def is_complete(self):
self.mutex.acquire()
try:
return self.response_code != -1
finally:
self.mutex.release()
def _ensure_request_complete(self):
if not self.is_complete():
raise Exception("Cannot access response until request is complete.")
def get_response_code(self):
self._ensure_request_complete()
return self.response_code
def get_response_message(self):
self._ensure_request_complete()
return self.response_message
def get_response_header_names(self):
self._ensure_request_complete()
output = list(self.response_headers_formatting.values())
output.sort()
return output
def get_response_header(self, name):
self._ensure_request_complete()
return self.response_headers_values.get(name.lower(), None)
def get_response_content(self, mode='t'):
self._ensure_request_complete()
output = self.response_content
if mode == 't':
return output.decode('utf-8')
else:
return output
def set_header(self, key, value):
self.header_formatting[key.lower()] = key
self.header_values[key.lower()] = [value]
def add_header(self, key, value):
canonical_key = key.lower()
existing_headers = self.header_values.get(canonical_key, None)
if existing_headers == None:
self.set_header(key, value)
else:
existing_headers.append(value)
def clear_header(self, key):
canonical_key = key.lower()
if self.header_values.get(canonical_key, None) != None:
self.header_values.pop(canonical_key)
self.header_formatting.pop(canonical_key)
def set_method(self, method):
self.method = method
def set_content(self, content):
self.content = content
def _init_query(self):
if self.query == None:
query = [] if self.original_query != '' else self.original_query.split('&')
lookup_values = {}
for item in query:
parts = item.split('=')
if len(parts) >= 2:
item_key = decode_url_value(parts[0])
item_value = decode_url_value('='.join(parts[1:]))
existing_values = lookup_values.get(item_key, None)
if existing_values == None:
existing_values = []
lookup_values[item_key] = existing_values
existing_values.append(item_value)
self.query = lookup_values
def set_query(self, key, value):
self._init_query()
self.query[key] = [value]
def add_query(self, key, value):
self._init_query()
values = self.query.get(key, None)
if values != None:
values.append(value)
else:
self.query[key] = [value]
def clear_query(self, key):
self._init_query()
if self.query.get(key, None) != None:
self.query.pop(key)
def set_port(self, port):
self.port = port
def set_fragment(self, fragment):
self.fragment = fragment
def clear_fragment(self):
self.fragment = None
def set_scehem(self, scheme):
self.scheme = scheme