/
choose
executable file
·273 lines (232 loc) · 9.16 KB
/
choose
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
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2012-2014 Christian Geier and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""simple chooser program
reads lines from stdin, lets user choose one line in an urwid (ncurses like)
interface, prints it to stdout and exits. Input will be aligned to tabs '\t'.
It does read and write directly into the currently active tty, thus working
like this: `get_data | choose | process_data`
"""
from __future__ import print_function
import os
import re
import sys
import urwid
def get_terminal_size():
""" taken from
http://stackoverflow.com/questions/566746/566752#566752
by user Johannes Weiss http://stackoverflow.com/users/55925/johannes-weiss
"""
env = os.environ
def ioctl_GWINSZ(filedesc):
try:
import fcntl
import termios
import struct
con_props = struct.unpack('hh', fcntl.ioctl(filedesc,
termios.TIOCGWINSZ,
'1234'))
except IOError:
return None
return con_props
con_props = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not con_props:
try:
filedesc = os.open(os.ctermid(), os.O_RDONLY)
con_props = ioctl_GWINSZ(filedesc)
os.close(filedesc)
except IOError:
pass
if not con_props:
try:
con_props = (env['LINES'], env['COLUMNS'])
except:
con_props = (25, 80)
return int(con_props[1]), int(con_props[0])
def get_terminal_size_wrapper():
"""wrapper function, if we are on py3.3+ it will use the build in function,
otherwise our own"""
try:
# python3.3+
import shutil
termsize = shutil.get_terminal_size()
return termsize.columns, termsize.lines
except AttributeError:
return get_terminal_size()
def select_entry(names, header_text=''):
"""interactive href selector (urwid based)
returns: href
return type: string
"""
class SelText(urwid.Text):
"""Selectable Text, saving index"""
def __init__(self, text):
urwid.Text.__init__(self, text)
self.orig_text = text
self.selected = False
@classmethod
def selectable(cls):
"""needs to be implemented"""
return True
def keypress(self, _, key):
"""needs to be implemented"""
if key == 'enter':
raise Selected(self.orig_text)
return key
class Selected(Exception):
"""used for signalling that an item was chosen in urwid"""
def __init__(self, exit_token=None):
self.exit_token = exit_token
class MyFrame(urwid.Frame):
def __init__(self, filterfun=None, backtrackfun=None, *args, **kwargs):
self._filter = filterfun
self._backtrack = backtrackfun
super(MyFrame, self).__init__(*args, **kwargs)
def keypress(self, size, key):
if key not in ['enter', 'esc', 'down', 'up', 'left', 'right', 'backspace', 'delete']:
out = self._footer.keypress([1], key=key)
self._filter(self.footer.text)
return out
elif key == 'backspace':
self._backtrack()
out = self._footer.keypress([1], key=key)
else:
return super(MyFrame, self).keypress(size, key)
class MySimpleListWalker(urwid.SimpleListWalker):
original_content = None
_out = list()
def filter_regex(self, string):
start, end = '', ''
self._out.append(list())
string = string.lower()
if len(string) and string[0] == '^':
string = string[1:]
start = '^'
if len(string) and string[-1] == '$':
string = string[:-1]
end = '$'
if string[0] in '\'"':
quote = string[0]
string = string[1:]
else:
quote = False
if quote and string and string[-1] == quote:
regex = start + '.*' + string[:-1] + '.*' + end
else:
regex = start + '.*'.join(string) + end
regex = re.compile(regex)
length = len(self.contents)
for num, line in enumerate(self.contents[::-1]):
text = line.original_widget.text.decode('utf-8').lower().strip()
if not regex.search(text):
self._out[-1].append(self.contents.pop(length - num - 1))
def backtrack(self):
if len(self._out) and isinstance(self._out[-1], list):
self.contents.extend(self._out.pop())
if len(names) is 1:
return names[0]
if names == list():
return None
name_list = list()
for one in names:
name_list.append(SelText(one))
palette = [
('header', 'white', 'black'),
('reveal focus', 'black', 'dark cyan', 'standout'),
]
content = MySimpleListWalker(
[urwid.AttrMap(w, None, 'reveal focus') for w in name_list])
listbox = urwid.ListBox(content)
header = urwid.Text(header_text, wrap='clip')
head = urwid.AttrMap(header, 'header')
foot = urwid.Edit()
top = MyFrame(content.filter_regex, content.backtrack, listbox, head, footer=foot)
def keystroke(input):
"""used for urwid test
to be removed
"""
if input in ['q', 'esc']:
raise urwid.ExitMainLoop()
loop = urwid.MainLoop(top, palette, unhandled_input=keystroke)
try:
loop.run()
except Selected as error:
return error.exit_token
def do_it(choice):
width, _ = get_terminal_size_wrapper()
def get_lengths(choice):
"""return max lengths of strings in 'columns' """
# list() for python3 compat.
return list(map(max, list(zip(*[map(len, one) for one in choice]))))
# main work is done here
choice = choice.split('\n')[:-1] # last line is always empty
choice = [one.split('\t') for one in choice]
# make sure all have elements have the same number of elements
number_elements = max([len(one) for one in choice])
for ind, _ in enumerate(choice):
while len(choice[ind]) < number_elements:
choice[ind].append('')
lengths = get_lengths(choice)
number_columns = len(lengths)
number_splits = number_columns - 1
while sum(lengths) + number_splits > width:
missing = width - sum(lengths) - number_splits
number_offenders = 0
for length in lengths:
if length > width / number_columns + number_splits:
number_offenders = number_offenders + 1
for ind, length in enumerate(lengths):
if length > width / number_columns + number_splits:
lengths[ind] = lengths[ind] + missing / number_offenders
break
# set length of column[i] to length[i], either clip or extent
choice = [[s[:length].ljust(length + 1) for s, length in list(zip(wahl, lengths))] for wahl in choice]
choice = [''.join(elemente) for elemente in choice]
out = select_entry(
choice, header_text=(
u'Navigate by pressing ↑ and ↓, search (fuzzy) by entering letters, '
'select by pressing Enter')
)
return out
class StreamTo(object):
def __init__(self, stdout='/dev/tty', stdin='/dev/tty'):
self._stdout = stdout
self._stdin = stdin
def __enter__(self):
self.old_out = sys.stdout
self.old_in = sys.stdin
sys.__stdout__ = sys.stdout = open(self._stdout, 'w')
sys.__stdin__ = sys.stdin = open(self._stdin)
os.dup2(sys.stdin.fileno(), 0)
os.dup2(sys.stdout.fileno(), 1)
def __exit__(self, exc_type, exc_value, traceback):
sys.stdout.flush()
sys.stdin.close()
sys.stdout.close()
sys.__stdout__ = sys.stdout = self.old_out
sys.__stdin__ = sys.stdin = self.old_in
if __name__ == "__main__":
choice = sys.stdin.read()
with StreamTo():
choice = do_it(choice)
if choice is not None:
sys.stderr.write(choice + '\n')