-
Notifications
You must be signed in to change notification settings - Fork 10
/
execute.py
461 lines (384 loc) · 15.4 KB
/
execute.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
# (c) 2013 Marcos Dione <mdione@grulic.org.ar>
# This file is part of ayrton.
#
# ayrton is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ayrton is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ayrton. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import io
from collections.abc import Iterable
import signal
# import logging
# logging.basicConfig(filename='tmp/bar.log',level=logging.DEBUG)
import ayrton
encoding= sys.getdefaultencoding ()
# special value to signal that the output should be captured
# instead of going to stdout
class Capture:
pass
# same, but for a pipe
class Pipe:
pass
class o (object):
def __init__ (self, **kwargs):
option= list (kwargs.items ())[0]
self.key= option[0]
self.value= option[1]
class CommandFailed (Exception):
def __init__ (self, command):
self.command= command
def __str__ (self):
return "%s: %d" % (' '.join ([ repr (arg) for arg in self.command.args]), self.command._exit_code)
class CommandNotFound (NameError):
def __init__ (self, name):
self.name= name
def __str__ (self):
return "CommandNotFound or NameError: command %(name)s not found or name %(name)s is not defined" % self.__dict__
def which(program):
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
if "PATH" not in os.environ:
return None
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def resolve_program(program):
path = which(program)
if not path:
# our actual command might have a dash in it, but we can't call
# that from python (we have to use underscores), so we'll check
# if a dash version of our underscore command exists and use that
# if it does
if "_" in program:
path = which(program.replace("_", "-"))
if not path:
return None
return path
class Command:
default_options= dict (
_in_tty= False,
_out_tty= False,
_env= {},
_end= os.linesep.encode (encoding),
_chomp= True,
_encoding= encoding,
_bg= False,
_fails= False,
)
supported_options= ('_in', '_out', '_err', '_end', '_chomp', '_encoding',
'_env', '_bg', '_fails')
def __init__ (self, path):
self.path= path
self.exe= resolve_program (path)
self.command= None
self.stdin_pipe= None
self.stdout_pipe= None
self.stderr_pipe= None
self._exit_code= None
self.capture_file= None
self.child_pid= None
def prepare_fds (self):
if '_in' in self.options:
i= self.options['_in']
if ( not isinstance (i, io.IOBase) and
type (i)!=int and
i is not None and
not isinstance (i, Command) ):
if self.options['_in_tty']:
# TODO: no support yet for input from file when _in_tty
# NOTE: os.openpty() returns (master, slave)
# but when writing master=w, slave=r
(master, slave)= os.openpty ()
self.stdin_pipe= (slave, master)
else:
# logging.debug ("prepare_fds: _in::%s creates a pipe()", type (i))
self.stdin_pipe= os.pipe ()
elif isinstance (i, Command):
if i.options.get ('_out', None)==Capture:
# if it's a captured command, create a pipe to feed the data
# logging.debug ("prepare_fds: _in::Command, _in._out==Capture creates a pipe()")
self.stdin_pipe= os.pipe ()
elif i.options.get ('_out', None)==Pipe:
# if it's a piped command, use its pipe and hope it runs in the bg
# logging.debug ("prepare_fds: _in::Command uses the stdout_pipe")
self.stdin_pipe= i.stdout_pipe
if '_out' in self.options:
if self.options['_out']==Capture:
if self.options['_out_tty']:
if self.options['_in_tty']:
# we use a copy of the pty created for the stdin
self.stdout_pipe= (os.dup (self.stdin_pipe[1]),
os.dup (self.stdin_pipe[0]))
else:
# this time the order is right
(master, slave)= os.openpty ()
self.stdout_pipe= (master, slave)
else:
# logging.debug ("prepare_fds: _out==Capture creates a pipe()")
self.stdout_pipe= os.pipe ()
elif self.options['_out']==Pipe:
# this pipe should be picked up by the outer Command
# logging.debug ("prepare_fds: _out==Pipe creates a pipe()")
self.stdout_pipe= os.pipe ()
if '_err' in self.options:
if self.options['_err']==Capture:
# if stdout is also Capture'd, then use the same pipe
if not '_out' in self.options or self.options['_out']!=Capture:
# if stdout is a tty, hook to that one
if self.options['_out_tty']:
self.stderr_pipe= (os.dup (self.stdout_pipe[0]),
os.dup (self.stdout_pipe[1]))
else:
# logging.debug ("prepare_fds: _err==Capture creates a pipe()")
self.stderr_pipe= os.pipe ()
elif self.options['_err']==Pipe:
# this pipe should be picked up by the outer Command
# logging.debug ("prepare_fds: _err==Pipe creates a pipe()")
self.stderr_pipe= os.pipe ()
def child (self):
if '_in' in self.options:
i= self.options['_in']
if i is None:
# connect to /dev/null
# it's not /dev/zero, see man (4) zero
i= open (os.devnull, 'rb')
if isinstance (i, io.IOBase):
# this does not work with file like objects
# dup its fd int stdin (0)
# logging.debug ("child: _in::IOBase redirects file to stdin")
os.dup2 (i.fileno (), 0)
i.close ()
elif type (i)==int:
# logging.debug ("child: _in::int redirects fd to stdin")
os.dup2 (i, 0)
os.close (i)
else:
# use the pipe prepared by prepare_fds()
# including the case where _in::Command
# logging.debug ("child: _in::%s, redirect stdin_pipe from prepare_fds() to stdin", type (i))
r, w= self.stdin_pipe
os.dup2 (r, 0)
os.close (r)
# the write fd can already be closed in this case:
# a= cat (..., _out=capture)
# b= grep (..., _in= a)
# once a's lines have been read, t
os.close (w)
if '_out' in self.options:
o= self.options['_out']
if o is None:
# connect to /dev/null
o= open (os.devnull, 'wb') # no need to create it
if isinstance (o, io.IOBase):
# this does not work with file like objects
# dup its fd in stdout (1)
# logging.debug ("child: _out::IOBase, redirects stout to file")
os.dup2 (o.fileno (), 1)
o.close ()
elif type (o)==int:
# logging.debug ("child: _out::int, redirects stdout to fd")
os.dup2 (o, 1)
os.close (o)
elif o==Capture or o==Pipe:
# logging.debug ("child: _out::(Capture or Pipe), stdout -> stdout_pipe")
r, w= self.stdout_pipe
os.dup2 (w, 1)
os.close (w)
os.close (r)
elif type (o) in (bytes, str):
# BUG: this is inconsistent with _in::str
# logging.debug ("child: _out::str, open file and redirect ")
f= open (o, 'w+')
os.dup2 (f.fileno (), 1)
f.close ()
if '_err' in self.options:
e= self.options['_err']
if e is None:
# connect to /dev/null
e= open (os.devnull, 'wb') # no need to create it
if isinstance (e, io.IOBase):
# this does not work with file like objects
# dup its fd int stderr (2)
os.dup2 (e.fileno (), 2)
if e==Capture:
if '_out' in self.options and self.options['_out']==Capture:
# send it to stdout
os.dup2 (1, 2)
else:
r, w= self.stderr_pipe
os.dup2 (w, 2)
os.close (r)
# restore some signals
for i in (signal.SIGPIPE, signal.SIGINT):
signal.signal (i, signal.SIG_DFL)
try:
os.execvpe (self.exe, self.args, self.options['_env'])
except FileNotFoundError:
os._exit (127)
def prepare_args (self, cmd, args, kwargs):
ans= [cmd]
for arg in args:
if type (arg)==o:
self.prepare_arg (ans, arg.key, arg.value)
else:
ans.append (str (arg))
for k, v in kwargs.items ():
self.prepare_arg (ans, k, v)
return ans
def prepare_arg (self, seq, name, value):
if value!=False:
seq.append (name)
# this is not the same as 'not value'
# because value can have any, well, value of any kind
if value!=True:
seq.append (str (value))
else:
# TODO: --no-option?
pass
def parent (self):
if self.stdin_pipe is not None:
# str -> write into the fd
# list -> write each
# file -> take fd
i= self.options['_in']
r, w= self.stdin_pipe
os.close (r)
if type (i)==str:
os.write (w, i.encode (encoding))
os.write (w, self.options['_end'])
elif type (i)==bytes:
os.write (w, i)
os.write (w, self.options['_end'])
elif isinstance (i, Iterable) and (not isinstance (i, Command) or
i.options.get ('_out', None)==Capture):
# this includes file-like's and Capture'd Commands
for e in i:
os.write (w, str (e).encode (encoding))
os.write (w, self.options['_end'])
elif not isinstance (i, Command):
os.write (w, str (i).encode (encoding))
os.write (w, self.options['_end'])
os.close (w)
# TODO: The return status of a pipeline is the exit status of the last
# command, unless the pipefail option is enabled. If pipefail is enabled,
# the pipeline's return status is the value of the last (rightmost)
# command to exit with a non-zero status, or zero if all commands exit
# successfully.
if not self.options['_bg']:
self.wait ()
ayrton.runner.wait_for_pending_children ()
else:
ayrton.runner.pending_children.append (self)
def wait (self):
self._exit_code= os.waitpid (self.child_pid, 0)[1] >> 8
reader_pipe= None
if self.stdout_pipe is not None:
# this will also read stderr if both are Capture'd
reader_pipe= self.stdout_pipe
if self.stderr_pipe is not None:
reader_pipe= self.stderr_pipe
if reader_pipe is not None and self.options.get ('_out', None)!=Pipe:
r, w= reader_pipe
os.close (w)
self.capture_file= open (r)
if self._exit_code==127:
# NOTE: when running bash, it returns 127 when it can't find the script to run
raise CommandNotFound (self.path)
if (ayrton.runner.options.get ('errexit', False) and
self._exit_code!=0 and
not self.options.get ('_fails', False)):
raise CommandFailed (self)
def exit_code (self):
if self._exit_code is None:
self.wait ()
return self._exit_code
def __call__ (self, *args, **kwargs):
if self.exe is None:
raise CommandNotFound (self.path)
self.options= self.default_options.copy ()
for option in self.supported_options:
try:
# update with the passed value
self.options[option]= kwargs[option]
# we don't need the option anymore
del kwargs[option]
except KeyError:
# ignore
pass
self.options['_env'].update (os.environ)
self.args= self.prepare_args (self.exe, args, kwargs)
self.stdin_pipe= None
self.stdout_pipe= None
self.stderr_pipe= None
self._exit_code= None
self.capture_file= None
self.prepare_fds ()
if type (self.options['_end'])!=bytes:
self.options['_end']= str (self.options['_end']).encode (encoding)
r= os.fork ()
if r==0:
self.child ()
else:
self.child_pid= r
self.parent ()
return self
def __bool__ (self):
if self._exit_code is None:
self.wait ()
return self._exit_code==0
def __str__ (self):
if self._exit_code is None:
self.wait ()
return self.capture_file.read ()
def __iter__ (self):
if self._exit_code is None:
self.wait ()
if self.capture_file is not None:
for line in self.capture_file.readlines ():
if self.options['_chomp']:
line= line.rstrip (os.linesep)
yield line
# finish him!
self.capture_file.close ()
else:
# TODO
pass
# BUG this method is leaking an opend file()
# self.capture_file
def readline (self):
if self._exit_code is None:
self.wait ()
line= self.capture_file.readline ()
if self.options['_chomp']:
line= line.rstrip (os.linesep)
return line
def close (self):
if self._exit_code is None:
self.wait ()
self.capture_file.close ()
def readlines (self):
if self._exit_code is None:
self.wait ()
# ugly way to not leak the file()
return ( line for line in self )
def __del__ (self):
# finish it
if self._exit_code is None and self.child_pid is not None:
self.wait ()