/
shell_turtlestein.py
193 lines (165 loc) · 7.04 KB
/
shell_turtlestein.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
import os.path, pipes, re, subprocess, tempfile
import sublime, sublime_plugin
from functools import partial
from sublime_readline import show_input_panel_with_readline
def cwd_for_window(window):
"""
Return the working directory in which the window's commands should run.
In the common case when the user has one folder open, return that.
Otherwise, return one of the following (in order of preference):
1) One of the open folders, preferring a folder containing the active
file.
2) The directory containing the active file.
3) The user's home directory.
"""
folders = window.folders()
if len(folders) == 1:
return folders[0]
else:
active_view = window.active_view()
active_file_name = active_view.file_name() if active_view else None
if not active_file_name:
return folders[0] if len(folders) else os.path.expanduser("~")
for folder in folders:
if active_file_name.startswith(folder):
return folder
return os.path.dirname(active_file_name)
def abbreviate_user(path):
"""
Return a path with the ~ dir abbreviated (i.e. the inverse of expanduser)
"""
home_dir = os.path.expanduser("~")
if path.startswith(home_dir):
return "~" + path[len(home_dir):]
else:
return path
def settings():
return sublime.load_settings('Shell Turtlestein.sublime-settings')
def cmd_settings(cmd):
"""
Return the default settings with settings for the command merged in
"""
d = {}
for setting in ['exec_args', 'surround_cmd', 'encoding']:
d[setting] = settings().get(setting)
try:
settings_for_cmd = (c for c
in settings().get('cmd_settings')
if re.search(c['cmd_regex'], cmd)).next()
d.update(settings_for_cmd)
except StopIteration:
pass
return d
def parse_cmd(cmd_str):
return re.match(
r"\s*(?P<input>\|)?\s*(?P<shell_cmd>.*?)\s*(?P<output>[|>])?\s*$",
cmd_str
).groupdict()
def run_cmd(cwd, cmd, wait, input_str=None):
shell = isinstance(cmd, basestring)
if wait:
proc = subprocess.Popen(cmd, cwd=cwd,
shell=shell,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=(subprocess.PIPE if input_str else None))
encoded_input = None if input_str == None else input_str.encode('utf8')
output, error = proc.communicate(encoded_input)
return_code = proc.poll()
if return_code:
show_in_output_panel("`%s` exited with a status code of %s\n\n%s"
% (cmd, return_code, error))
return (False, None)
else:
return (True, output.decode('utf8'))
else:
subprocess.Popen(cmd, cwd=cwd, shell=shell)
return (False, None)
def show_in_output_panel(message):
window = sublime.active_window()
panel_name = 'shell_turtlestein'
panel = window.get_output_panel(panel_name)
edit = panel.begin_edit()
panel.insert(edit, 0, message)
panel.end_edit(edit)
window.run_command('show_panel', {'panel': 'output.' + panel_name})
class ShellPromptCommand(sublime_plugin.WindowCommand):
"""
Prompt the user for a shell command to run in the window's directory
"""
def run(self):
if not hasattr(self, 'cmd_history'):
self.cmd_history = []
cwd = cwd_for_window(self.window)
on_done = partial(self.on_done, cwd)
inputview = show_input_panel_with_readline(self.window,
abbreviate_user(cwd) + " $",
self.cmd_history,
on_done, None, None)
for (setting, value) in settings().get('input_widget').iteritems():
inputview.settings().set(setting, value)
def on_done(self, cwd, cmd_str):
cmd = parse_cmd(cmd_str)
if not cmd['input'] and cmd['output'] == '|':
sublime.error_message(
"Piping output to the view requires piping input from the view as well."
+ " Please use a preceding |.")
return
active_view = self.window.active_view()
if cmd['input'] or cmd['output'] == '|':
if not active_view:
sublime.error_message(
"A view has to be active to pipe text from and/or to a view.")
return
settings = cmd_settings(cmd['shell_cmd'])
before, after = settings['surround_cmd']
shell_cmd = before + cmd['shell_cmd'] + after
if cmd['input']:
input_regions = [sel for sel in active_view.sel() if sel.size() > 0]
if len(input_regions) == 0:
input_regions = [sublime.Region(0, active_view.size())]
else:
input_regions = None
# We can leverage Sublime's (async) build systems unless we're
# redirecting the output into a view. In that case, we use Popen
# synchronously.
if cmd['output']:
for region in (input_regions or [None]):
self.process_region(active_view, region, cwd, shell_cmd, cmd['output'])
else:
if input_regions:
# Since Sublime's build system doesn't support piping to STDIN
# directly, use a tempfile.
text = "".join([active_view.substr(r) for r in input_regions])
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(text.encode('utf8'))
shell_cmd = "%s < %s" % (shell_cmd, pipes.quote(temp.name))
exec_args = settings['exec_args']
exec_args.update({'cmd': shell_cmd, 'shell': True, 'working_dir': cwd})
if settings['encoding']:
exec_args.update({'encoding': settings['encoding']})
self.window.run_command("exec", exec_args)
def process_region(self, active_view, selection, cwd, shell_cmd, outpt):
input_str = None
if selection:
input_str = active_view.substr(selection)
(success, output) = run_cmd(cwd, shell_cmd, True, input_str)
if success:
if outpt == '|':
edit = active_view.begin_edit()
active_view.replace(edit, selection, output)
active_view.end_edit(edit)
elif outpt == '>':
self.window.run_command("new_file")
new_view = self.window.active_view()
new_view.set_name(shell_cmd.strip())
edit = new_view.begin_edit()
new_view.insert(edit, 0, output)
new_view.end_edit(edit)
class SubprocessInCwdCommand(sublime_plugin.WindowCommand):
"""
Launch a subprocess using the window's working directory
"""
def run(self, cmd=None, wait=False):
cwd = cwd_for_window(self.window)
run_cmd(cwd, cmd, wait)