-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathmix_format_file.py
98 lines (75 loc) · 2.65 KB
/
mix_format_file.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
import os
from os import path
import sublime
import sublime_plugin
import subprocess
class MixFormatFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
window = self.view.window()
window.run_command("save")
window.run_command("mix_format_file_without_save")
class MixFormatOnSave(sublime_plugin.EventListener):
def on_post_save(self, view):
syntax = view.settings().get('syntax')
if syntax.find('Elixir.tmLanguage') != -1:
settings = sublime.load_settings('Elixir.sublime-settings')
if settings.get('mix_format_on_save', False):
view.run_command('mix_format_file_without_save')
if settings.get('reload_after_mix_format', False):
view.run_command("revert")
class MixFormatFileWithoutSaveCommand(sublime_plugin.TextCommand):
def run(self, edit):
window = self.view.window()
settings = sublime.load_settings('Elixir.sublime-settings')
# Hide the console window on Windows
shell = False
path_separator = ':'
if os.name == 'nt':
shell = True
path_separator = ';'
file_name = self.view.file_name()
cwd = self.find_cwd(window, settings, file_name)
if settings.get('make_path_relative', False):
file_name = self.make_path_relative(file_name, cwd)
cmd = settings.get('mix_format_command', 'mix format').split(' ') + [file_name]
p = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
cwd=cwd
)
_, stderrdata = p.communicate()
stderrdata = stderrdata.strip()
if stderrdata:
panel_view = window.create_output_panel('mix_format')
panel_view.set_read_only(False)
panel_view.run_command('erase_view')
panel_view.run_command('append', {'characters': stderrdata.decode()})
panel_view.set_read_only(True)
window.run_command('show_panel', {'panel': 'output.mix_format'})
else:
window.run_command('hide_panel', {'panel': 'output.mix_format'})
window.status_message('Formatting successful!')
def find_cwd(self, window, settings, file_name):
cur_dir = path.dirname(file_name)
cwd = os.path.expanduser("~")
for root_path in window.folders():
if cur_dir.startswith(root_path):
cwd = root_path
break
if settings.get('use_root_dir', False):
cwd
else:
while cwd != cur_dir:
if path.isfile(path.join(cur_dir, 'mix.exs')):
cwd = cur_dir
break
else:
cur_dir = path.dirname(cur_dir)
if cur_dir == "/":
cwd
break
return cwd
def make_path_relative(self, file_name, cwd):
return file_name.replace(cwd, '.')