/
minion.py
335 lines (243 loc) · 10.2 KB
/
minion.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
import sublime, sublime_plugin
import subprocess
import re, os, os.path
import itertools
from User.build import *
from User.output import *
import traceback
def make_build_system_name(system, variant):
if system.endswith('.'):
return "{} - {}".format(system[:-1], variant)
else:
return "{} - {}".format(system[:], variant)
class Window:
def __init__(self, window):
self.window = window
def __getattr__(self, name):
return getattr(self.window, name)
def get_working_dir(self):
build_systems = self.project_data()["build_systems"]
for build_system in build_systems:
if "working_dir" in build_system:
return sublime.expand_variables(build_system["working_dir"], self.extract_variables())
return None
class MinionClearViewCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.erase(edit, sublime.Region(0, self.view.size()))
class MinionPanelAppendCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
scroll = self.view.visible_region().end() == self.view.size()
self.view.insert(edit, self.view.size(), text)
if scroll:
self.view.show(self.view.size())
class MinionBuildCommand(sublime_plugin.WindowCommand):
def __init__(self, *args):
super().__init__(*args)
self.build_system = None
def build_systems(self):
window = self.window
build_systems_data = self.window.project_data()["build_systems"]
build_systems_data = expand_variables_ex(build_systems_data, window.extract_variables())
build_systems = {}
for data in build_systems_data:
for key, value in data.items():
if key == "variants":
for variant in value:
build_systems[make_build_system_name(data["name"], variant["name"])] = variant
else:
try:
build_systems[data["name"]][key] = value
except KeyError:
build_systems[data["name"]] = { key : value }
return build_systems
def run_build(self, config):
self.window.run_command("save_all")
config["command"] = config["cmd"]
self.window.run_command(
"minion_generic_build",
{ "config" : config })
def is_project_opened(self):
return self.window.project_data() != None
def run_file_build(self):
view = self.window.active_view()
if view.file_name().endswith(".cpp"):
print("Not implemented")
else:
print("Not implemented")
def is_latex_project(self):
return "latex" in self.window.project_data()
def build_latex_project(self):
self.window.run_command("minion_build_latex")
def run(self):
if self.is_latex_project():
self.window.run_command("save_all")
self.build_latex_project()
elif self.is_project_opened():
window = self.window
OutputView.request().clear()
build_systems = self.build_systems()
if self.build_system in build_systems:
self.run_build(build_systems[self.build_system])
else:
build_system_names = sorted(list(build_systems.keys()))
def on_done(index):
self.build_system = build_system_names[index]
self.run_build(build_systems[self.build_system])
window.show_quick_panel(build_system_names, on_done)
else:
self.run_file_build()
class MinionCancellBuildCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("minion_generic_build");
class MinionFocusSublimeCommand(sublime_plugin.WindowCommand):
def window_name(self):
active = self.window.active_view()
project = os.path.basename(self.window.project_file_name())
project = project.replace(".sublime-project", "")
if active and active.file_name():
home = os.path.expanduser("~")
path = active.file_name().replace(home, "~")
return "{} ({}) - Sublime Text".format(path, project)
else:
return "untitled ({}) - Sublime Text".format(project)
def run(self, depth = 3):
subprocess.check_call(["wmctrl", "-a", self.window_name()])
if depth:
args = ("minion_focus_sublime", { "depth" : depth - 1 })
sublime.set_timeout_async(lambda: self.window.run_command(*args), 333)
def get_working_dir():
window = sublime.active_window()
if window.project_data():
build_systems = window.project_data()["build_systems"]
for build_system in build_systems:
if "working_dir" in build_system:
return sublime.expand_variables(build_system["working_dir"], window.extract_variables())
view = window.active_view()
return os.path.dirname(view.file_name())
class MinionCommand(sublime_plugin.WindowCommand):
def __init__(self, window):
super().__init__(window)
def _active_view_dir(self):
view = self.window.active_view()
return os.path.dirname(view.file_name())
def _makefile_exists(self):
pass
def run(self, **kwargs):
if "working_dir" not in kwargs or kwargs["working_dir"] == "":
kwargs["working_dir"] = self._active_view_dir()
self.window.run_command(
"minion_generic_build",
{ "config" : kwargs })
class MinionFormatCommand(sublime_plugin.WindowCommand):
def __init__(self, window):
super().__init__(window)
def _get_syntax(self):
view = self.window.active_view()
syntax = view.settings().get('syntax')
return os.path.splitext(os.path.basename(syntax))[0]
def _active_file(self):
view = self.window.active_view()
return view.file_name()
def run(self, **kwargs):
syntax = self._get_syntax()
if syntax == "C++":
self.window.run_command("save")
subprocess.call(["clang-format-3.8", "-i", "-style=Google", self._active_file()])
self.window.active_view().set_status("minion-format", "clang-format-3.8: DONE...")
def erase_status():
self.window.active_view().erase_status("minion-format")
sublime.set_timeout(erase_status, 4096)
class MinionDetectCpp(sublime_plugin.EventListener):
@staticmethod
def is_cpp(view):
pass
def detect_cpp(self, view):
if (os.path.splitext(view.file_name())[1] == "" and
view.settings().get('syntax') == "Packages/Text/Plain text.tmLanguage" and
not view.find("#pragma|#include", 0).empty()):
view.set_syntax_file("Packages/C++/C++.tmLanguage")
def on_load(self, view):
self.detect_cpp(view)
def on_post_save(self, view):
self.detect_cpp(view)
def walk_project_files(path):
IGNORE = ".git"
stack = [path]
full_path = [path]
while stack != []:
top = stack[-1]
stack.pop()
for file in os.listdir(top):
full = os.path.join(top, file)
if os.path.isdir(full):
if (not file.startswith(".") and
file not in IGNORE):
stack.append(full)
else:
yield full
def is_source(path):
if not path:
return False
return path.endswith(".cpp") or path.endswith(".c") or path.endswith(".cxx")
def is_header(path):
if not path:
return False
ext = os.path.splitext(path)[1]
if (ext == ""):
file = open(path, "r")
try:
for line in itertools.islice(file.readlines(), 32):
if "#pragma" in line:
return True
except:
return False
return False
else:
return ext == ".hpp" or ext == ".h" or ext == ".hxx"
class MinionToggleHeader(sublime_plugin.WindowCommand):
@staticmethod
def find_the_other(window, path, predicate):
variables = window.extract_variables()
if "project_path" in variables:
project_path = variables["project_path"]
elif "folder" in variables:
project_path = variables["folder"]
source_base = os.path.splitext(os.path.basename(path))[0]
for entry in walk_project_files(project_path):
if predicate(entry):
header_base = os.path.splitext(os.path.basename(entry))[0]
if header_base == source_base:
return entry
return None
def toggle(self, view):
target = None
if is_header(view.file_name()):
target = MinionToggleHeader.find_the_other(self.window, view.file_name(), is_source)
elif is_source(view.file_name()):
target = MinionToggleHeader.find_the_other(self.window, view.file_name(), is_header)
if target:
self.window.open_file(target)
self.window.status_message("Toggle to {}...".format(os.path.basename(target)))
else:
self.window.status_message("Cannot toggle...")
def run(self, **kwargs):
self.toggle(self.window.active_view())
class MinionBuildCurrentFile(sublime_plugin.WindowCommand):
def make(self, view):
target = view.file_name()
if is_header(target):
target = MinionToggleHeader.find_the_other(self.window, target, is_source)
if is_source(target):
working_dir = self.window.extract_variables()["project_path"]
dirname, basename = os.path.split(os.path.splitext(target)[0])
object_file = os.path.join(dirname, "build", basename) + ".o"
object_file = os.path.relpath(object_file, working_dir)
config = {
"working_dir" : working_dir,
"cmd" : ["make", object_file] }
self.window.run_command("minion_generic_build", { "config" : config })
self.window.status_message("Building {}...".format(os.path.basename(target)))
def run(self, **kwargs):
if self.window.active_view().is_dirty():
self.window.run_command("save")
self.make(self.window.active_view())