-
Notifications
You must be signed in to change notification settings - Fork 5
/
itermoxyl
executable file
·267 lines (212 loc) · 9.49 KB
/
itermoxyl
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
#!/usr/bin/env python2.7
import argparse
import re
import signal
import subprocess
import sys
import glob
import os
from math import ceil
from os.path import expanduser, normpath, join
VERSION_MAJOR = 1
VERSION_MINOR = 2
VERSION_PATCH = 0
CONFIG_PATH = expanduser("~/.ssh/")
home = expanduser("~")
host_re = re.compile(r"host\s+([^\s*?]+)", re.IGNORECASE)
include_re = re.compile(r"include\s+(.*)", re.IGNORECASE)
hostname_re = re.compile(r"hostname\s+(\S+)", re.IGNORECASE)
# this regexp will extract a integer suffix, if ones exists, then use
# the prefix as first sorting field and the suffix and the second one
host_split = re.compile(r"(\D+(?:\d+\D+)*)(\d+)")
comma_list_of_indexes = re.compile(r"(?:\d+(?:-\d+)?)(?:,\d+(?:-\d+)?)*") # e.g.: 1,3-5,7-11,20,30-100
item_range = re.compile(r"(\d+)-(\d+)")
parser = argparse.ArgumentParser(
description="Tool to automatically open several ssh connections in iTerm2 by querying ~/.ssh/config. "
"Check https://github.com/luciopaiva/itermoxyl for more details.")
parser.add_argument("-r", "--run", dest="should_actually_run", action="store_true", default=False,
help="Must pass this to actually run, otherwise will just list matching hosts")
parser.add_argument("-d", "--debug", action="store_true", default=False,
help="Just dump Applescript, do not execute")
parser.add_argument("-v", "--version", action="store_true", default=False, help="Just print version and exit")
parser.add_argument("pattern", nargs='*', help="Regular expression used to filter hosts by name. You can provide "
"multiple regexps separated by spaces and they will be concatenated "
"internally using `.*?`.", default=None)
arguments = parser.parse_args()
# noinspection PyUnusedLocal
def signal_handler(sig, frame):
# Gracefully exit if Ctrl+C is pressed
exit(0)
def load_hosts(config_file_name="config", available_hosts=None):
""" Here we collect all hosts available in ~/.ssh/config.
"""
with open(normpath(join(CONFIG_PATH, expanduser(config_file_name)))) as f:
if available_hosts is None:
available_hosts = set()
current_host = None
for line in f.readlines():
# skip comment lines
line = line.strip()
if line.startswith("#"):
continue
result = include_re.search(line)
if result:
for arg in result.group(1).replace('=', ' ').split(' '):
if arg.startswith('~'):
arg = os.path.expanduser(arg)
elif not arg.startswith('/'):
arg = CONFIG_PATH + arg
for f in list(glob.glob(arg)):
load_hosts(f, available_hosts)
# look for `Host` lines
result = host_re.search(line)
if result:
current_host = result.group(1)
elif current_host is not None:
# for a host to be selected, it must have a `HostName` property
result = hostname_re.search(line)
if result:
available_hosts.add(current_host)
return available_hosts
def check_if_iterm_version_is_supported():
osa = subprocess.Popen(['osascript', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
version_script = 'set iterm_version to (get version of application "iTerm")'
version = str(osa.communicate(bytes(version_script))[0]).strip()
match = re.search(r"^(\d+)\.(\d+)", version)
if match:
major = int(match.group(1))
minor = int(match.group(2))
return (major > 2) or (major == 2 and minor > 9) # support only if greater than 2.9
return False
def prompt_for_confirmation(hosts_count):
print("\nNumber of panes to open: %d" % hosts_count)
sys.stdout.write("Press 'y' to continue (or any other key to abort): ")
choice = raw_input().strip().lower()
return choice == "y"
def create_pane(parent, child, orientation):
return """
tell pane_{parent}
set pane_{child} to (split {orientation}ly with same profile)
end tell
""".format(parent=parent, child=child, orientation=orientation)
def init_pane(number, host):
return """
tell pane_{number}
write text "ssh {host}"
set name to "${host}"
end tell
""".format(number=number, host=host)
def prepare_and_run_applescript(selected_hosts):
num_panes = len(selected_hosts)
vertical_splits = int(ceil((num_panes / 2.0))) - 1
second_columns = num_panes // 2
pane_creation = ""
for p in range(0, vertical_splits):
parent = (p * 2) + 1
child = parent + 2
pane_creation += create_pane(parent, child, "horizontal")
for p in range(0, second_columns):
parent = (p * 2) + 1
child = parent + 1
pane_creation += create_pane(parent, child, "vertical")
pane_initialization = ""
for i in range(0, num_panes):
pane_initialization += init_pane(i + 1, selected_hosts[i])
script = """
tell application "iTerm"
activate
tell current window
create tab with default profile
end tell
set pane_1 to (current session of current window)
{pane_creation}
{pane_initialization}
end tell
""".format(pane_creation=pane_creation, pane_initialization=pane_initialization)
if arguments.debug:
print(script)
exit(0)
osa = subprocess.Popen(['osascript', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
output = osa.communicate(bytes(script))[0]
print(output)
def split_host_by_prefix_and_suffix(host):
""" This is a hack to get hosts correctly ordered by number. When ordering, we'd expect "foo1, foo2, ... foo10", but
when we order lexicographically, we get "foo1, foo10, foo2, ...". So this method splits the common prefix apart
from the number suffix (in case there is one), then order first by the prefix and if there's a draw, order by
suffix.
"""
result = host_split.match(host)
if result:
prefix = result.group(1)
suffix = int(result.group(2)) if result.group(2) else 0
else:
prefix = host
suffix = 0
return prefix, suffix
def sort_hosts(selected_hosts):
return sorted(selected_hosts, key=lambda host: split_host_by_prefix_and_suffix(host))
def try_last_term_as_list_of_indexes(pattern):
if len(pattern) > 1: # must have at least one term before
list_of_indexes = comma_list_of_indexes.match(pattern[-1]) # try to match a special term at the end
if list_of_indexes is not None:
# last pattern term is a list of ids, treat it differently
list_of_indexes = list_of_indexes.group(0).split(",")
expanded_list = []
for item in list_of_indexes:
range_result = item_range.match(item)
if range_result is not None:
range_begin = int(range_result.group(1))
range_end = int(range_result.group(2))
if range_begin > range_end:
print("Range '{}' is invalid".format(item))
exit(1)
for i in range(range_begin, range_end + 1):
expanded_list.append(str(i))
else:
expanded_list.append(item)
# replace the original special term with its resulting regular expression
# the RE matches any number in the list as long as it:
# 1. is not preceded by a numeric digit
# 2. is at the very end of the name of the machine
pattern[-1] = r"(?<!\d)(?:{})$".format("|".join(expanded_list))
return True
return False
def try_expand_list_of_names(pattern, look_at_last_term):
for i in range(0, len(pattern)):
if not look_at_last_term and i == len(pattern):
break
term = pattern[i]
if "," in term:
pattern[i] = "(?:{})".format(term.replace(",", "|"))
def main():
if arguments.version:
print("{}.{}.{}".format(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH))
exit(0)
if not check_if_iterm_version_is_supported():
print("iTerm2 version not supported or not installed")
exit(1)
if type(arguments.pattern) is not list or len(arguments.pattern) == 0:
parser.print_help()
exit(1)
has_list_of_indexes = try_last_term_as_list_of_indexes(arguments.pattern)
try_expand_list_of_names(arguments.pattern, has_list_of_indexes)
loose_search = ".*?".join(["(?:{})".format(p) for p in arguments.pattern])
pat = re.compile(loose_search, re.IGNORECASE)
available_hosts = load_hosts()
# get filtered list of hosts, each a tuple (name, address)
selected_hosts = list(host for host in available_hosts if pat.search(host))
if len(selected_hosts) == 0:
print("There are no hosts that match the given filter.")
exit(0)
selected_hosts = sort_hosts(selected_hosts)
print("Will open the following terminal panes:\n")
for host in selected_hosts:
print("- %s" % host)
if arguments.debug or prompt_for_confirmation(len(selected_hosts)):
prepare_and_run_applescript(selected_hosts)
signal.signal(signal.SIGINT, signal_handler)
main()