-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrolex.py
executable file
·1308 lines (1110 loc) · 42.4 KB
/
rolex.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from ConfigParser import RawConfigParser
from contextlib import contextmanager
from cStringIO import StringIO
from datetime import datetime
from difflib import SequenceMatcher
from Queue import Queue, Empty
from subprocess import check_output, CalledProcessError, Popen, PIPE
from threading import Event, Thread
import argparse
import curses
import curses.textpad
import os
import re
import time
import locale
locale.setlocale(locale.LC_ALL, "")
class Command(object):
"""
A shell command that `rolex` periodically runs. Configures the way the
command is run, and also tracks some state, like the output of the last n
runs of the command.
"""
def __init__(self, command, period, running):
self.command = command
self.period = period
self.running = running
self.content = []
self.mark = None
self.started = time.ctime()
self.last_update = time.ctime()
self.runner = None
self.terminated = False
self.scheduled_run = Event()
self.on_error = None
self.on_change = None
self.active = True
self.latch = Event()
self.friendly_time = False
def start_runner(self, queue):
"""
Starts a thread that periodically runs the command.
`queue` is the queue into which the command's output is placed after
each run.
"""
self.runner = spawn(self._run, queue)
def stop_runner(self):
"""
Stops the thread that runs the command, as when the user kills the pane
that's showing this command. If there isn't a thread currently running,
this does nothing.
"""
self.terminated = True
def toggle_running(self):
"""
Toggles the active state of the command, for pausing/unpausing this
command independently of the others.
"""
self.set_running(not self.active)
def set_running(self, running):
"""
Sets the active state of the command to `running`.
"""
self.active = running
if self.active:
self.latch.set()
else:
self.latch.clear()
def change_period(self, amount):
"""
Changes the command's period by `amount`. (A positive amount makes the
command run less frequently.)
It is not possible to have a period shorter than one second.
"""
self.period = max(1, self.period + amount)
def set_diff_mark(self):
"""
Sets the output of the command's last run as the "mark" for diffing
against, i.e., the UI will show diffs against the point in time just
before this function was called.
"""
if self.content:
self.mark = self.content[-1].splitlines()
def clear_diff_mark(self):
"""
Clears the diff mark set by `set_diff_mark`. If there isn't a diff
mark, this does nothing.
"""
self.mark = None
def trigger_rerun(self, reset_schedule=False):
"""
Signals for the command to be run again more or less immediately.
If `reset_schedule` is True, the next command won't run again for
approximately `self.period` seconds. Otherwise, next run will occur
when it normally would have.
"""
self.scheduled_run.set()
self.latch.set()
if reset_schedule:
self.next_run = time.time()
@property
def diff_base_output(self):
"""
The output, as a list of strings, to diff against.
If a diff mark has been set, returns that. Otherwise, returns the
output from two runs ago (to compare against the most recent output),
or None if there isn't enough output for that.
"""
if self.mark is not None:
return self.mark
if len(self.content) < 2:
return None
return self.content[-2].splitlines()
def last_update_text(self, use_since=False):
"""
Returns a string representation of the last time a command was run.
"""
return self.last_update
def wait_until_next_run(self, now):
"""
Waits until the time of the next scheduled rerun (or returns
immediately if that time is in the past).
Returns True if the command should be run again, False if it doesn't
need to.
"""
result = self.scheduled_run.wait(self.next_run - now)
return self.latch.is_set() and (result or self.next_run - now > 0)
def _get_output(self):
"""
Runs the command, returning its output and True.
If the command failed to run, returns an error message and False
instead.
"""
try:
with open(os.devnull, 'w') as devnull:
output = check_output(self.command, stderr=devnull, shell=True)
return output, True
except CalledProcessError, e:
return "Error running '%s':\n\n%s" % (self.command, e), False
def _record_output(self, output):
changed = self.content and (output != self.content[-1])
# TODO diff against last, store time and data
self.content.append(output)
if len(self.content) > 60:
self.content.pop(0)
return changed
def _compute_next_run(self, now):
next_run = self.next_run
while next_run < now:
next_run += max(1, self.period)
return next_run
def _handle_result(self, handler, queue):
if handler[0] == 'exit':
queue.put(('exit', self))
elif handler[0] == 'pause':
queue.put(('pause', self))
elif handler[0] == 'exec':
Popen(handler[1], shell=True)
elif handler[0] == 'exec_and_pause':
queue.put(('pause', self))
Popen(handler[1], shell=True)
def _run(self, queue):
"""
Periodically runs the command (forever), adding its output to `queue`.
This is intended to run in a separate greenlet/thread/process.
"""
self.trigger_rerun(reset_schedule=True)
while True:
if self.terminated:
break
now = time.time()
if self.wait_until_next_run(now):
output, success = self._get_output()
if not success and self.on_error is not None:
self._handle_result(self.on_error, queue)
self.last_update = time.ctime()
changed = self._record_output(output)
if changed and self.on_change is not None:
self._handle_result(self.on_change, queue)
queue.put(('output', (self, output)))
self.scheduled_run.clear()
self.next_run = self._compute_next_run(now)
self.running.wait()
if not self.active:
self.latch.clear()
else:
self.latch.set()
self.latch.wait()
class Pane(object):
"""
A fixed slice of the UI, to which information about a `Command` can be
rendered.
This manages a curses pad, rendering to that off-screen and then drawing
the pad into the correct part of the screen.
"""
def __init__(self, index, height, width, layout):
"""
- `index` is 0 for the topmost pane on the screen, 1 for the one below
that, etc.
- `height` is the height of the pane, in terminal rows
- `width` is the width of the pane, in terminal columns
- `layout` is the layout manager for the pane
"""
self.index = index
self.show_diffs = False
self.pattern = None
self.graph = False
self.browsing = False
self.browsing_at = -1
self.selected = False
self.layout = layout
self.resize(height, width)
def resize(self, height, width):
"""
Adjusts the height and width of the pane to be `height` terminal rows
and `width` columns.
"""
self.height = height
self.width = width
self.pad = curses.newpad(height, width)
def draw_header(self, command, use_unicode=True, use_since=False):
"""
Renders the header for the command to the internal curses pad.
- `command` is the Command object to show in this pane.
- `use_unicode` determines whether Unicode characters can be used to
help draw the header
- `use_since` determines whether the header timestamp is shown in
absolute time or relative time
"""
# Draw a full-width separator.
separator = u'\u2500' if use_unicode else '-'
self.pad.addstr(0, 0,
(separator * self.width).encode('utf-8'),
curses.color_pair(2))
# Write the command's period.
pos = 2 # margin
self.pad.addstr(0, pos, str(command.period),
curses.color_pair(1) | curses.A_BOLD)
pos += len(str(command.period)) + 1
# Attributes for the command depend on whether it's running and/or
# selected.
attrs = curses.color_pair(3)
if not command.running.is_set() or not command.active:
attrs = curses.color_pair(4) | curses.A_BOLD
if self.selected:
attrs |= curses.A_UNDERLINE
# Write the command.
self.pad.addstr(0, pos, command.command, attrs)
pos += len(command.command) + 1
if self.browsing:
self.pad.addstr(0, pos, 'browse', curses.color_pair(1))
pos += len('browse') + 1
if command.on_error is not None:
msg = 'err:' + command.on_error[0]
self.pad.addstr(0, pos, msg, curses.color_pair(1))
pos += len(msg) + 1
if command.on_change is not None:
msg = 'chg:' + command.on_change[0]
self.pad.addstr(0, pos, msg, curses.color_pair(1))
pos += len(msg) + 1
# Add markers for other states.
if self.graph:
self.pad.addstr(0, pos, 'graph', curses.color_pair(1))
elif self.show_diffs:
diff_str = 'diff last' if not command.mark else 'diff mark'
self.pad.addstr(0, pos, diff_str, curses.color_pair(1))
elif self.pattern:
self.pad.addstr(0, pos, self.pattern, curses.color_pair(1))
# Write the command's last run time, right-aligned.
last_update = command.last_update_text(use_since=use_since)
self.pad.addstr(0, self.width - len(last_update) - 1, last_update)
def draw_wait(self):
"""
Draws a "waiting" banner in the center of the pane.
"""
output = [''] * (self.height / 2 - 2)
output.append('Waiting for output...'.center(self.width))
self.draw_output(output)
def draw_graph(self, output):
"""
Renders `output`, which is assumed to be a list of string lines
containing floating point values, as an ASCII/Unicode time-series bar
graph.
"""
lines = (line for line in (line.strip() for line in output) if line)
graph = Graph(self.height - 3, self.width - 1, lines, y_offset=2)
graph.render(self.pad)
def draw_output(self, output, diff_base=None, history=None):
"""
Draws the output of a command, as a list of strings, to the pane.
If `diff_base` (a list of strings) is given, the differences between
`output` and `diff_base` are highlighted.
"""
# Clear the pane, except the header.
self.pad.move(1, 0)
self.pad.clrtobot()
if self.graph and self.pattern and history:
# TODO None -> unknown (for gap in graph)
pattern_matches = [
re.findall('[-0-9.]+', match[0])[0] for match in
(re.findall(self.pattern, line)
for output in history for line in output.splitlines())
if match]
return self.draw_graph(pattern_matches)
elif self.graph:
return self.draw_graph(output)
for lineno, line in enumerate(output[-(self.height - 2):]):
# Write the line, making sure it can fit in the pane.
truncline = line.rstrip()[:self.width - 1]
self.pad.addstr(2 + lineno, 1, truncline)
# Highlight diffs if we're in diff mode and have something to diff
# against.
if self.show_diffs and diff_base and lineno < len(diff_base):
diffline = diff_base[lineno][:self.width - 1]
for pos, substr in get_diffs(diffline, truncline):
self.pad.addstr(2 + lineno, 1 + pos, substr,
curses.color_pair(5) | curses.A_BOLD)
# Highlight pattern matches if we have a pattern.
elif self.pattern:
for pos, substr in get_matches(self.pattern, truncline):
self.pad.addstr(2 + lineno, 1 + pos, substr,
curses.color_pair(5) | curses.A_BOLD)
def refresh(self, command):
"""
Redraws the header and output area for `command`, but does not commit.
"""
self.draw_header(command)
if not command.content:
self.draw_wait()
else:
self.draw_output(command.content[-1].splitlines(),
diff_base=command.diff_base_output,
history=command.content)
def commit(self):
"""
Writes the changes to the pad out to the window, but doesn't redraw.
"""
self.layout.commit(self.pad, self.index, self.height, self.width)
class EvenVerticalLayout(object):
"""
A layout that draws panes full-width, stacking them equally-sized
vertically.
"""
def size(self, size, index, height, width):
return height / size, width
def commit(self, pad, index, height, width):
pad.noutrefresh(0, 0,
index * height, 0,
(index + 1) * height - 2, width)
class EvenHorizontalLayout(object):
"""
A layout that draws panes full-height, stacking them equally-sized
horizontally.
"""
def size(self, size, index, height, width):
return height, width / size
def commit(self, pad, index, height, width):
pad.noutrefresh(0, 0,
0, index * width,
height, (index + 1) * width - 2)
class Graph(object):
"""
Renders a time-series bar graph from a set of points.
"""
def __init__(self, graph_height, graph_width, values,
y_offset=1, x_offset=1, y_labels=4):
self.graph_height = graph_height
self.graph_width = graph_width
self.y_offset = y_offset
self.x_offset = x_offset
self.y_labels = y_labels
self.points = [float(value) for value in values]
# Collapse (average) adjacent points if we have more points than
# available width for each one to have a bar.
if self.graph_width < len(self.points):
points_per_col = len(self.points) / float(self.graph_width)
points_per_col = max(2, int(round(points_per_col)))
new_points = []
for i in range(0, len(self.points), points_per_col):
col_slice = self.points[i:i + points_per_col]
new_points.append(sum(col_slice) / float(len(col_slice)))
self.points = new_points
@property
def bar_width(self):
"""
Computes the width of a bar in the graph, to come as close as possible
to filling the allowed width.
"""
return max(1, self.graph_width / len(self.points))
def render(self, pad, fill=u'\u2592'):
"""
Renders the bar to `pad`, using `fill` as the character to draw bars.
"""
min_point, max_point = min(self.points), max(self.points)
# Set up a matrix of characters (all spaces at first).
graph = [[' ' for _ in range(self.graph_width)]
for _ in range(self.graph_height)]
# Update the matrix with the fill char.
delta = max(1, (max_point - min_point))
for col, point in enumerate(self.points):
for col_offset in range(self.bar_width):
pct_height = (point - min_point) / delta
bar_height = int(pct_height * self.graph_height)
for row in range(bar_height):
y = self.graph_height - 1 - row
x = col * self.bar_width + col_offset
graph[y][x] = fill
# Render the matrix to the curses pad.
graph_lines = (u''.join(line).encode('utf8') for line in graph)
for lineno, line in enumerate(graph_lines):
pad.addstr(self.y_offset + lineno, self.x_offset, line)
# Render y-axis labels.
for label in range(self.y_labels + 1):
pct = float(label) / self.y_labels
y = 1 + int(self.graph_height * (1 - pct))
pad.addstr(y, 1, str(min_point + pct * delta))
def get_matches(pattern, line):
"""
Generates pairs of (column, matching substring) each match of the regular
expression `pattern` in the string `line`.
"""
for match in re.finditer(pattern, line):
yield match.start(), line[match.start():match.end()]
def get_diffs(old_line, new_line):
"""
Generates pairs of (column, different substring) for each diff between the
strings `old_line` and `new_line`.
"""
sm = SequenceMatcher(a=old_line, b=new_line)
for tag, _, _, j1, j2 in sm.get_opcodes():
if tag not in ('replace', 'insert'):
continue
yield j1, new_line[j1:j2]
class Screen(object):
"""
Provides some high level functions around a curses screen.
"""
@staticmethod
@contextmanager
def configure(colors):
"""
A context manager that sets up a screen, yields it, and cleans the
screen up when finished (ensuring that the terminal is usable again).
Like `curses.wrapper` but a bit more tailored.
- `colors` is a list of (foreground color, background color) pairs
"""
screen = curses.initscr()
curses.start_color()
for i, (fg, bg) in enumerate(colors, start=1):
curses.init_pair(i, fg, bg)
curses.noecho()
curses.cbreak()
curses.curs_set(0)
screen.keypad(1)
try:
yield Screen(screen)
finally:
screen.keypad(0)
curses.nocbreak()
curses.echo()
curses.endwin()
def __init__(self, screen):
"""
- `screen` is a curses screen, as from `curses.initscr`
"""
self._screen = screen
self.update_size()
def get_keys(self, queue):
"""
Reads keystrokes from the screen (forever), and adds them to `queue`.
This is intended to run in a separate greenlet/thread/process.
"""
self._screen.nodelay(1)
esc = False
while True:
ch = self._screen.getch()
if ch == -1:
time.sleep(0.1)
elif ch == 27:
esc = True
else:
queue.put(('key', ch if not esc else 'M-' + chr(ch)))
esc = False
def update_size(self):
"""
Updates the size of the terminal in which `rolex` is running.
"""
self.height, self.width = self._screen.getmaxyx()
def message_user(self, message_string, delay=3):
"""
Writes a message to the user at the bottom of the screen, erasing it
after `delay` seconds.
(Currently, there is no protection from overwriting other messages or
prompts.)
"""
self._screen.addstr(self.height - 1, 0, message_string)
self._screen.refresh()
spawn(self._destroy_message, delay)
def _destroy_message(self, delay):
"""
Erases the message set by `message_user` after `delay` seconds.
"""
time.sleep(delay)
self._screen.move(self.height - 1, 0)
self._screen.clrtobot()
def prompt_user(self, prompt_string, default_value):
"""
Prompt the user with a bar at the bottom of the screen.
`prompt_string` is the uneditable string displayed at the left-hand
side of the bar, and `default_value` (if given) is the editable string
that populates the bar.
"""
self._screen.addstr(self.height - 1, 0, prompt_string)
self._screen.refresh()
# Create a window at the bottom of the screen, set the default value,
# wrap it in a Textbox.
textwin = curses.newwin(1, self.width, self.height - 1,
len(prompt_string))
textwin.addstr(0, 0, default_value or '')
textbox = curses.textpad.Textbox(textwin)
curses.curs_set(1)
try:
result = textbox.edit().strip()
finally:
curses.curs_set(0)
# Erase the bar.
self._screen.move(self.height - 1, 0)
self._screen.clrtobot()
return result
def clear_and_refresh(self):
"""
Clear the screen immediately.
"""
self._screen.clear()
self._screen.refresh()
class Watch(object):
"""
Ties together a screen, list of commands, and a list of panes.
"""
def __init__(self, screen, running, commands, queue):
"""
- `screen` is a `Screen` object
- `running` is an `Event` that can be used to pause commands
- `commands` is an initial list of `Command` objects to run
- `queue` is a queue that the screen and commands will use to send key
presses and command output
"""
self.screen = screen
self.commands = commands
self.queue = queue
self.running = running
self.layout = LAYOUTS[0]
self.panes = [Pane(i, 1, 1, self.layout) for i in range(len(commands))]
self.panes[0].selected = True
# This maps pane index to the command to show in that pane, so we can
# rearrange them.
self.pane_map = dict(enumerate(self.commands))
self.adjust_pane_sizes()
@contextmanager
def suspended(self):
"""
A context manager that pauses all commands for the duration of the
execution of the `with` block and allows other applications to take
over the screen.
"""
curses.def_prog_mode()
self.screen.clear_and_refresh()
self.running.clear()
try:
yield
finally:
self.running.set()
curses.reset_prog_mode()
self.screen.clear_and_refresh()
def set_selected_from_key(self, key):
"""
Sets the selected pane from the keycode `key`.
So, if `key` is the keycode for "2", the command currently in the
second pane from the top is selected (and all others are deselected).
"""
for i, pane in enumerate(self.panes):
pane.selected = i == int(chr(key)) - 1
def add_pane_and_command(self, command, period):
"""
Adds `command` to run every `period` seconds in a new pane.
"""
pane = Pane(len(self.panes), 1, 1, self.layout)
self.panes.append(pane)
command = Command(command, period, self.running)
command.start_runner(self.queue)
self.commands.append(command)
self.pane_map = dict(enumerate(self.commands))
def remove_pane(self, pane):
"""
Removes the Pane object `pane`, so that it no longer renders, and its
associated command, so that it no longer runs.
"""
command = self.pane_map[pane.index]
mirrored = any(c == command
for index, c in self.pane_map.items()
if index != pane.index)
self.panes.remove(pane)
for i, p in enumerate(self.panes):
p.index = i
if not mirrored:
command.stop_runner()
self.commands.remove(command)
self.pane_map = dict(enumerate(self.commands))
if not self.selected and self.panes:
self.panes[0].selected = True
return len(self.commands) == 0
def set_layout(self, new_layout):
"""
Sets `new_layout` as the new layout to use when drawing the screen,
and immediately resizes/redraws all panes accordingly.
"""
self.layout = new_layout
for pane in self.panes:
pane.layout = new_layout
self.adjust_pane_sizes()
def adjust_pane_sizes(self):
"""
Resize all panes so that they're all evenly about (screen height / # of
commands) rows high.
"""
self.screen.update_size()
self.screen.clear_and_refresh()
if not self.commands:
return
for pane, command in self:
new_height, new_width = self.layout.size(len(self.panes),
pane.index,
self.screen.height,
self.screen.width)
pane.resize(new_height, new_width)
pane.refresh(command)
pane.commit()
def __iter__(self):
"""
Generate a list of pairs of (Pane object, Command object for the
command that runs in that pane).
"""
for i, command in sorted(self.pane_map.iteritems()):
yield self.panes[i], command
def panes_for_command(self, command):
"""
Generates the Pane objects to which the Command `command` currently
renders.
"""
for i, c in self.pane_map.iteritems():
if c == command:
yield self.panes[i]
@property
def selected(self):
"""
The pair (Pane object for currently selected pane, Command object for
command that runs in that pane), or None.
"""
for pane, command in self:
if pane.selected:
return pane, command
@property
def selected_command(self):
"""
Returns just the command part of `self.selected`.
"""
_, command = self.selected
return command
@property
def selected_and_mirrors(self):
"""
Returns a list of pairs of (pane, command) for the selected pane and
any panes containing commands mirrored from the selected one.
"""
selected_pane, selected_command = self.selected
return [(pane, command) for pane, command in self
if pane is selected_pane or command is selected_command]
def cmd_select(watch, key):
"""
Sets the selected command given the keycode `key` (where "1" selects the
command in the topmost pane, "2" selects the one below that, etc.).
"""
watch.set_selected_from_key(key)
for pane, command in watch:
pane.draw_header(command)
pane.commit()
def cmd_toggle_pause(watch, key):
"""
Toggles the "paused" flag for all commands.
"""
all_active = all(command.active for _, command in watch)
for pane, command in watch:
command.set_running(not all_active)
pane.draw_header(command)
pane.commit()
def cmd_toggle_pause_one(watch, key):
"""
Toggles the "paused" flag for the selected commands.
"""
pane, command = watch.selected
command.toggle_running()
for pane, command in watch.selected_and_mirrors:
pane.draw_header(command)
pane.commit()
def cmd_period_change(amount):
"""
Updates the period of execution for the selection command,
adjusting it by `amount`.
"""
def _cmd(watch, key):
watch.selected_command.change_period(amount)
for pane, command in watch.selected_and_mirrors:
pane.draw_header(command)
pane.commit()
return _cmd
def cmd_toggle_diffs(watch, key):
"""
Toggles diff mode for the command in the selected pane. If diffs of any
kind are enabled (diff last or diff mark), they are disabled; otherwise,
diff last is enabled.
"""
pane, command = watch.selected
command.clear_diff_mark()
pane.show_diffs = not pane.show_diffs
pane.draw_header(command)
pane.commit()
def cmd_edit_pattern(watch, key):
"""
Opens a prompt to set or edit a regular expression for highlighting the
output of the selected pane's command.
"""
pane, command = watch.selected
new_pattern = watch.screen.prompt_user('Pattern: ', pane.pattern or '')
pane.pattern = new_pattern or None
pane.refresh(command)
pane.commit()
def cmd_edit_command(watch, key):
"""
Opens a prompt to set or edit the command that runs in the selected pane.
"""
pane, command = watch.selected
new_command = watch.screen.prompt_user('Command: ', command.command)
if not new_command:
return
command.command = new_command
command.trigger_rerun(reset_schedule=True)
def cmd_add_command(watch, key):
"""
Opens a series of prompts to start periodically running a new command in a
new pane.
"""
command = watch.screen.prompt_user('Run: ', '')
if not command:
return
try:
period = int(watch.screen.prompt_user('Period: ', ''))
except ValueError:
return
watch.add_pane_and_command(command, period)
watch.adjust_pane_sizes()
def cmd_kill_command(watch, key):
"""
Kills the selected pane and stops running the command it contains.
"""
pane, _ = watch.selected
if watch.remove_pane(pane):
return True
watch.adjust_pane_sizes()
def cmd_mirror_command(watch, key):
"""
Opens a new pane, the display of which is linked to the output of the
selected pane's command.
"""
pane, command = watch.selected
watch.panes.append(Pane(len(watch.commands), 1, 1, pane.layout))
watch.pane_map[len(watch.pane_map)] = command
watch.adjust_pane_sizes()
def cmd_mark_diff(watch, key):
"""
Enables diff mark mode in the selected pane. This diffs all future output
of the command in that pane against the output that is currently show
there.
"""
pane, command = watch.selected
pane.show_diffs = True
command.set_diff_mark()
pane.draw_header(command)
pane.commit()
def cmd_force_run(with_reset):
"""
Forces the command in the selected pane to run immediately. This does not
alter the time at which the next scheduled run of the command was supposed
to occur.
"""
def _cmd(watch, key):
_, command = watch.selected
command.trigger_rerun(reset_schedule=with_reset)
return _cmd
def cmd_show_help(watch, key):
"""
Shows the current keybindings. Uses $PAGER, or `less.
"""
with watch.suspended():
proc = Popen(os.environ.get('PAGER', 'less'), stdin=PIPE, shell=True)
proc.communicate(generate_help_text())
for pane, command in watch:
pane.draw_header(command)
pane.commit()
def cmd_toggle_graph(watch, key):
"""
Toggles graph mode for the command in the selected pane.
"""
pane, command = watch.selected
pane.graph = not pane.graph
command.trigger_rerun()
pane.draw_header(command)
pane.commit()
def cmd_cycle_layout(watch, key):
"""
Toggles graph mode for the command in the selected pane.
"""
new_layout = LAYOUTS[(LAYOUTS.index(watch.layout) + 1) % len(LAYOUTS)]
watch.set_layout(new_layout)
def cmd_rotate_panes(amount):
"""
Rotates panes, popping the first `amount` and tacking them on the end of
the ordered arrangement of panes.
"""
def _rotate(watch, key):
commands = [cmd for _, cmd in sorted(watch.pane_map.items())]
watch.pane_map = dict(enumerate(commands[amount:] + commands[:amount]))
watch.adjust_pane_sizes()
return _rotate
def cmd_back_output(watch, key):
"""
Puts the selected pane in "browsing mode" if it's not already, and shows
the output of the run before the one that's currently displayed.
"""
pane, command = watch.selected
pane.browsing = True
if pane.browsing_at > -len(command.content):
pane.browsing_at -= 1
pane.draw_header(command)
pane.draw_output(command.content[pane.browsing_at].splitlines(),
diff_base=command.diff_base_output)