-
Notifications
You must be signed in to change notification settings - Fork 215
/
cli.py
298 lines (265 loc) Β· 9.5 KB
/
cli.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
import argparse
import logging
import logging.config
from getpass import getuser
from os import environ, getcwd, path
from socket import gethostname
from subprocess import call
from sys import exit, stderr
from time import time
try:
from emoji import emojize
except ImportError:
emojize = None
try:
import psutil
except ImportError:
psutil = None
from . import __version__, notify
from .config import load_config, DEFAULT_CONFIG, OLD_DEFAULT_CONFIG
from .data import scripts
try:
from .terminal import is_focused
except ImportError:
is_focused = lambda: True
def run_cmd(args):
if getattr(args, 'pid', False):
return watch_pid(args)
if not args.command:
if args.formatter:
args.command, retcode, duration = args.formatter
args.command, retcode, duration = (
[args.command], int(retcode), int(duration))
else:
stderr.write('usage: ntfy done [-h|-L N] command\n'
'ntfy done: error: the following arguments '
'are required: command\n')
exit(1)
else:
start_time = time()
retcode = call(args.command)
duration = time() - start_time
if args.longer_than is not None and duration <= args.longer_than:
return
if args.unfocused_only and is_focused():
return
if emojize is not None and not args.no_emoji:
prefix = ':white_check_mark: ' if retcode == 0 else ':x: '
else:
prefix = ''
return '{}"{}" {} in {:d}:{:02d} minutes'.format(
prefix, ' '.join(args.command), 'succeeded' if retcode == 0 else
'failed', *map(int, divmod(duration, 60)))
def watch_pid(args):
if psutil is None: # pragma: no cover
logging.error(
"This command requires psutil module. Pleases install psutil.")
exit(1)
try:
p = psutil.Process(args.pid)
cmd = p.cmdline()
start_time = p.create_time()
except psutil.NoSuchProcess:
logging.error("PID {} not found".format(args.pid))
exit(1)
try:
p.wait()
except psutil.NoSuchProcess: # pragma: no cover
pass # this happens when the PID disapears
duration = time() - start_time
return 'PID[{}]: "{}" finished in {:d}:{:02d} minutes'.format(
p.pid, ' '.join(cmd), *map(int, divmod(duration, 60)))
def auto_done(args):
if args.longer_than:
print('export AUTO_NTFY_DONE_LONGER_THAN=-L{}'.format(args.longer_than))
if args.unfocused_only:
print('export AUTO_NTFY_DONE_UNFOCUSED_ONLY=-b')
if args.shell == 'bash':
print('source {}'.format(scripts['bash-preexec.sh']))
print('source {}'.format(scripts['auto-ntfy-done.sh']))
print("# To use ntfy's shell integration, run "
"this and and it to your shell's rc file:")
print('# eval "$(ntfy shell-integration)"')
class BackendOptionAction(argparse.Action):
backend = None
def __call__(self, parser, args, values, option_string=None):
if self.dest == 'backend':
self.__class__.backend = values
if args.backend is None:
args.backend = []
args.backend.append(values)
elif self.dest == 'option':
if args.option is None:
args.option = {}
args.option.setdefault(self.__class__.backend,
{})[values[0]] = values[1]
else:
raise Exception("'BackendOptionAction only supports dest of "
"'backend' and 'option'")
parser = argparse.ArgumentParser(
description='Send push notification when command finishes')
parser.add_argument(
'-c',
'--config',
help='config file to use (default: {})'.format(DEFAULT_CONFIG))
parser.add_argument('-b',
'--backend',
action=BackendOptionAction,
help='override backend specified in config')
parser.add_argument('-o',
'--option',
nargs=2,
default={},
action=BackendOptionAction,
metavar=('key', 'value'),
help='backend specific options')
parser.add_argument('-l',
'--log-level',
action='store',
default='WARNING',
choices=[
'CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'
],
help=('Specify the how verbose CLI output is '
'(default: WARNING)'))
parser.add_argument('-v',
'--verbose',
dest='log_level',
action='store_const',
const='DEBUG',
help='a shortcut for --log-level=DEBUG')
parser.add_argument('-q',
'--quiet',
dest='log_level',
action='store_const',
const='CRITICAL',
help='a shortcut for --log-level=CRITICAL')
parser.add_argument('--version', action='version', version=__version__)
if emojize is not None:
parser.add_argument('-E',
'--no-emoji',
action='store_true',
help='Disable emoji support')
default_title = '{}@{}:{}'.format(getuser(), gethostname(), getcwd().replace(
path.expanduser('~'), '~'))
parser.add_argument('-t',
'--title',
help='a title for the notification (default: {})'
.format(default_title))
subparsers = parser.add_subparsers()
send_parser = subparsers.add_parser('send', help='send a notification')
send_parser.add_argument('message', help='notification message')
send_parser.set_defaults(func=lambda args: args.message)
done_parser = subparsers.add_parser(
'done',
help='run a command and send a notification when done')
done_parser.add_argument('command',
nargs=argparse.REMAINDER,
help='command to run')
done_parser.add_argument(
'-L',
'--longer-than',
type=int,
metavar='N',
help="Only notify if the command runs longer than N seconds")
done_parser.add_argument(
'-b',
'--background-only',
action='store_true',
default=False,
dest='unfocused_only',
help="Only notify if shell isn't in the foreground")
done_parser.add_argument(
'--formatter',
metavar=('command', 'retcode', 'duration'),
nargs=3,
help="Format and send cmd, retcode & duration instead of running command. "
"Used internally by shell-integration")
if psutil is not None:
done_parser.add_argument(
'-p',
'--pid',
type=int,
help="Watch a PID instead of running a new command")
done_parser.set_defaults(func=run_cmd)
shell_integration_parser = subparsers.add_parser(
'shell-integration',
help='automatically get notifications when long running commands finish')
shell_integration_parser.add_argument(
'-s',
'--shell',
default=path.split(environ.get('SHELL', ''))[1],
choices=['bash', 'zsh'],
help='The shell to integrate ntfy with (default: $SHELL)')
shell_integration_parser.add_argument(
'-L',
'--longer-than',
type=int,
metavar='N',
help="Only notify if the command runs longer than N seconds")
shell_integration_parser.add_argument(
'-f',
'--foreground-too',
action='store_false',
default=True,
dest='unfocused_only',
help="Also notify if shell is in the foreground")
shell_integration_parser.set_defaults(func=auto_done)
def main(cli_args=None):
if cli_args is not None:
args = parser.parse_args(cli_args)
else:
args = parser.parse_args()
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(levelname)s: %(message)s'
},
},
'handlers': {
'default': {
'level': args.log_level,
'class': 'logging.StreamHandler',
'formatter': 'default',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': args.log_level,
'propagate': True,
}
}
})
if args.config is not None:
config = load_config(args.config)
elif path.exists(path.expanduser(DEFAULT_CONFIG)):
config = load_config(DEFAULT_CONFIG)
elif path.exists(path.expanduser(OLD_DEFAULT_CONFIG)):
config = load_config(OLD_DEFAULT_CONFIG)
else: # get default config and print message about missing file
config = load_config()
if args.backend:
config['backends'] = args.backend
for backend, backend_options in args.option.items():
if backend is not None:
config.setdefault(backend, {}).update(backend_options)
if getattr(args, 'func', None) == run_cmd and args.longer_than is None and \
'longer_than' in config:
args.longer_than = config['longer_than']
if args.title is None:
args.title = config.get('title', default_title)
if hasattr(args, 'func'):
message = args.func(args)
if message is None:
return 0
if emojize is not None and not args.no_emoji:
message = emojize(message, use_aliases=True)
return notify(message, args.title, config,
**dict(args.option.get(None, [])))
else:
parser.print_help()
if __name__ == '__main__':
exit(main())