-
Notifications
You must be signed in to change notification settings - Fork 2
/
padawan.py
283 lines (228 loc) · 7.89 KB
/
padawan.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
import sublime
from os import path
import json
import subprocess
import re
try:
from urllib.parse import urlencode
from urllib.request import urlopen
from urllib.request import Request
from urllib.request import URLError
except ImportError:
from urllib import urlencode
from urllib2 import urlopen
from urllib2 import Request
from urllib2 import URLError
def get_setting(name, default=None):
project_data = sublime.active_window().project_data()
if (project_data and 'padawan' in project_data and
name in project_data['padawan']):
return project_data['padawan'][name]
return sublime.load_settings('Padawan.sublime-settings').get(name, default)
server_addr = "http://127.0.0.1:15155"
cli = 'padawan'
server_command = 'padawan-server'
class Server:
def start(self):
subprocess.Popen(
server_command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
def stop(self):
try:
self.sendRequest('kill', {})
return True
except Exception:
return False
def restart(self):
if self.stop():
self.start()
def sendRequest(self, command, params, data=''):
timeout = get_setting("padawan_timeout", 0.5)
addr = server_addr + "/"+command+"?" + urlencode(params)
request = Request(addr, headers={
"Content-Type": "plain/text"
}, data = data.encode("utf8"))
response = urlopen(
request,
timeout=timeout
)
result = json.loads(response.read().decode("utf8"))
if "error" in result:
raise ValueError(result["error"])
return result
class Editor:
def getView(self):
return sublime.active_window().active_view()
def log(self, message):
print(message)
def notify(self, message):
self.getView().set_status("PadawanStatus", message)
def progress(self, progress):
bars = int(progress / 5)
bars_str = ''
for i in range(20):
if i < bars:
bars_str += '='
else:
bars_str += ' '
bars_str = '[' + bars_str + ']'
message = "Progress {0} {1}%".format(bars_str, str(progress))
self.getView().set_status("PadawanProgress", message)
return
def error(self, error):
self.notify(error)
def callAfter(self, timeout, callback):
def Notifier():
if callback():
sublime.set_timeout(Notifier, timeout)
sublime.set_timeout(Notifier, timeout)
server = Server()
editor = Editor()
pathError = '''padawan command is not found in your $PATH. Please\
make sure you installed padawan.php package and\
configured your $PATH'''
class PadawanClient:
def GetCompletion(self, filepath, line_num, column_num, contents):
curPath = self.GetProjectRoot(filepath)
params = {
'filepath': filepath.replace(curPath, ""),
'line': line_num,
'column': column_num,
'path': curPath
}
result = self.DoRequest('complete', params, contents)
if not result:
return {"completion": []}
return result
def SaveIndex(self, filepath):
return self.DoRequest('save', {'filepath': filepath})
def DoRequest(self, command, params, data=''):
try:
response = server.sendRequest(command, params, data)
editor.error("")
return response
except URLError:
editor.error("Padawan.php is not running")
except Exception as e:
editor.error("Error occured {0}".format(e))
return False
def AddPlugin(self, plugin):
composer = get_setting("padawan_composer", "composer")
composerCommand = composer + ' global require '
command = '{0} {2} && {1} plugin add {2}'.format(
composerCommand,
cli,
plugin
)
stream = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
def OnAdd(retcode):
if not retcode:
server.restart()
editor.notify("Plugin installed")
else:
if retcode == 127:
editor.error(pathError)
editor.error("Plugin installation failed")
def LogAdding():
retcode = stream.poll()
if retcode is not None:
return OnAdd(retcode)
line = stream.stdout.readline().decode("ascii")
editor.log(line)
return True
editor.callAfter(1e-4, LogAdding)
def RemovePlugin(self, plugin):
composer = get_setting("padawan_composer", "composer")
composerCommand = composer + ' global remove'
command = '{0} {1}'.format(
composerCommand,
plugin
)
stream = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
def onRemoved():
subprocess.Popen(
'{0}'.format(
cli + ' plugin remove ' + plugin
),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
).wait()
self.RestartServer()
return editor.notify("Plugin removed")
def LogRemoving():
retcode = stream.poll()
if retcode is not None:
return onRemoved()
line = stream.stdout.readline().decode("ascii")
editor.log(line)
return True
editor.callAfter(1e-4, LogRemoving)
def Generate(self, filepath):
curPath = self.GetProjectRoot(filepath)
stream = subprocess.Popen(
'cd ' + curPath + ' && ' + cli + ' generate',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
def onGenerationEnd(retcode):
if retcode > 0:
if retcode == 127:
editor.error(pathError)
else:
editor.error("Error occured, code: {0}".format(
str(retcode)
))
return
server.restart()
editor.progress(100)
editor.notify("Index generated")
def ProcessGenerationPoll():
retcode = stream.poll()
if retcode is not None:
return onGenerationEnd(retcode)
line = stream.stdout.readline().decode("utf8")
errorMatch = re.search('Error: (.*)', line)
if errorMatch is not None:
retcode = 1
editor.error("{0}".format(
errorMatch.group(1).replace("'", "''")
))
return
match = re.search('Progress: ([0-9]+)', line)
if match is None:
return True
progress = int(match.group(1))
editor.progress(progress)
return True
editor.callAfter(1e-4, ProcessGenerationPoll)
def StartServer(self):
server.start()
def StopServer(self):
server.stop()
def RestartServer(self):
server.restart()
def GetProjectRoot(self, filepath):
curPath = path.dirname(filepath)
while curPath != '/' and not path.exists(
path.join(curPath, 'composer.json')
):
curPath = path.dirname(curPath)
if curPath == '/':
curPath = path.dirname(filepath)
return curPath
client = PadawanClient()