aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/fancy-sleep
blob: 76cb04c620dab95144e371182e13f3bb86068344 (plain)
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
#!/usr/bin/env python3
# Copyright 2017 vg@devys.org
# SPDX-License-Identifier: MIT

'''
Simple and fancy sleep for console.

Time can be precised as XX[h|m|s] [YY[m|s]] [ZZ[s]] or XX:YY[:ZZ].

Usage: fancy-sleep [options] TIME...
       fancy-sleep -h|--help

Options:
  -h, --help  Display this help message
'''


import contextlib
import datetime
import sys
import time
import re

import docopt


_determine_delta_pattern = None


# to avoid accidental trailing spaces removal, use another character and
# replace.
numbers = [i.replace('.', ' ') for i in (
"""\
 ██████
 ██  ██
 ██  ██
 ██  ██
 ██████
""",
"""\
     ██
     ██
     ██
     ██
     ██
""",
"""\
 ██████
     ██
 ██████
 ██....
 ██████
""",
"""\
 ██████
     ██
 ██████
     ██
 ██████
""",
"""\
 ██  ██
 ██  ██
 ██████
     ██
     ██
""",
"""\
 ██████
 ██....
 ██████
     ██
 ██████
""",
"""\
 ██████
 ██....
 ██████
 ██  ██
 ██████
""",
"""\
 ██████
     ██
     ██
     ██
     ██
""",
"""\
 ██████
 ██  ██
 ██████
 ██  ██
 ██████
""",
"""\
 ██████
 ██  ██
 ██████
     ██
 ██████
""",
"""\
    .
  ██.
    .
  ██.
    .
""",
)]


def print_translated(string):
    translated = []
    for character in string:
        index = 0
        if '0' <= character and character <= '9':
            index = ord(character) - ord('0')
        elif character == ':':
            index = 10
        translated.append(numbers[index])
    display_lines = ['', '', '', '', '', '']
    for index in range(5):
        for number in translated:
            display_lines[index] += number.splitlines()[index]
    print('\n'.join(display_lines), end='')


def determine_delta(elements,
                    time_pattern=re.compile(r'^(\d+)([dhms]?)$')):
    default = datetime.datetime.strptime('0', '%S')
    timedelta = datetime.timedelta()
    for element in elements:
        groups = time_pattern.match(element)
        if groups:
            if groups.group(2) == 'd':
                timedelta += datetime.timedelta(days=float(groups.group(1)))
            elif groups.group(2) == 'h':
                timedelta += datetime.timedelta(hours=float(groups.group(1)))
            elif groups.group(2) == 'm':
                timedelta += datetime.timedelta(minutes=float(groups.group(1)))
            elif groups.group(2) == 's' or groups.group(2) == '':
                timedelta += datetime.timedelta(seconds=float(groups.group(1)))


        #with contextlib.suppress(ValueError):
        #    timedelta += datetime.datetime.strptime(element, '%dd') - default
        #with contextlib.suppress(ValueError):
        #    timedelta += datetime.datetime.strptime(element, '%Hh') - default
        #with contextlib.suppress(ValueError):
        #    timedelta += datetime.datetime.strptime(element, '%Mm') - default
        #with contextlib.suppress(ValueError):
        #    timedelta += datetime.datetime.strptime(element, '%Ss') - default
        #with contextlib.suppress(ValueError):
        #    timedelta += datetime.datetime.strptime(element, '%S') - default
        else:
            with contextlib.suppress(ValueError):
                timedelta += datetime.datetime.strptime(element, '%H:%M') - default
            with contextlib.suppress(ValueError):
                timedelta += datetime.datetime.strptime(element, '%H:%M:%S') - default
    return timedelta


def determine_delta_tests():
    assert(determine_delta('11'.split()) == datetime.timedelta(seconds=11))
    assert(determine_delta('11s'.split()) == datetime.timedelta(seconds=11))
    assert(determine_delta('11h 47m'.split()) == datetime.timedelta(hours=11, minutes=47))
    assert(determine_delta('11h 47'.split()) == datetime.timedelta(hours=11, seconds=47))
    assert(determine_delta('11h 47m 09'.split()) == datetime.timedelta(hours=11, minutes=47, seconds=9))
    assert(determine_delta('09:53'.split()) == datetime.timedelta(hours=9, minutes=53))
    assert(determine_delta('8:2 9'.split()) == datetime.timedelta(hours=8, minutes=2, seconds=9))
    assert(determine_delta('8d 5:32 6s'.split()) == datetime.timedelta(days=8, hours=5, minutes=32, seconds=6))


if __name__ == '__main__':
    'run fancy-sleep code: args parsing, display and sleeping logic'

    # FIXME: can be done automatically with nose for example ?
    determine_delta_tests()

    args = docopt.docopt(__doc__)

    curtime = datetime.datetime.now()
    timedelta = determine_delta(args['TIME'])
    target_time = curtime + timedelta

    print('Launched at:', curtime.strftime('%F %T'))
    print('Run until:', target_time.strftime('%F %T'))
    sys.stdout.flush()

    if sys.stdout.isatty():
        print()

        print('\n'*5, '\x1b[5A', sep='', end='')
        print('\x1b[s', end='') # save cursor
        try:
            while True:
                delta = target_time.timestamp() - time.time()
                if delta <= 0:
                    break
                hours = int(delta / 3600)
                minutes = int(delta / 60) % 60
                seconds = int(delta) % 60

                print('\x1b[u', end='') # restore cursor
                time_string = '%02d:%02d:%02d' % (hours, minutes, seconds)
                #print('\rremainining time: %s' % time_string, end='')
                print_translated(time_string)

                time.sleep(1)
        except KeyboardInterrupt:
            sys.exit(130)
        finally:
            print()
    else:
        try:
            time.sleep(target_time.timestamp() - time.time())
        except KeyboardInterrupt:
            sys.exit(130)