blob: e67ac159e5a0e9cfe401244f43c185c788766011 [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass0d24de92012-01-14 15:12:45 +00002# Copyright (c) 2011 The Chromium OS Authors.
3#
Simon Glass0d24de92012-01-14 15:12:45 +00004
5import os
Simon Glassbf776672020-04-17 18:09:04 -06006
7from patman import cros_subprocess
8from patman import tools
Simon Glass0d24de92012-01-14 15:12:45 +00009
10"""Shell command ease-ups for Python."""
11
Simon Glassa10fd932012-12-15 10:42:04 +000012class CommandResult:
13 """A class which captures the result of executing a command.
14
15 Members:
16 stdout: stdout obtained from command, as a string
17 stderr: stderr obtained from command, as a string
18 return_code: Return code from command
19 exception: Exception received, or None if all ok
20 """
21 def __init__(self):
22 self.stdout = None
23 self.stderr = None
Simon Glass82012dd2014-09-05 19:00:12 -060024 self.combined = None
Simon Glassa10fd932012-12-15 10:42:04 +000025 self.return_code = None
26 self.exception = None
27
Simon Glass82012dd2014-09-05 19:00:12 -060028 def __init__(self, stdout='', stderr='', combined='', return_code=0,
29 exception=None):
30 self.stdout = stdout
31 self.stderr = stderr
32 self.combined = combined
33 self.return_code = return_code
34 self.exception = exception
35
Simon Glass3b3e3c02019-10-31 07:42:50 -060036 def ToOutput(self, binary):
37 if not binary:
38 self.stdout = tools.ToString(self.stdout)
39 self.stderr = tools.ToString(self.stderr)
40 self.combined = tools.ToString(self.combined)
41 return self
42
Simon Glass82012dd2014-09-05 19:00:12 -060043
44# This permits interception of RunPipe for test purposes. If it is set to
45# a function, then that function is called with the pipe list being
46# executed. Otherwise, it is assumed to be a CommandResult object, and is
47# returned as the result for every RunPipe() call.
48# When this value is None, commands are executed as normal.
49test_result = None
Simon Glassa10fd932012-12-15 10:42:04 +000050
51def RunPipe(pipe_list, infile=None, outfile=None,
52 capture=False, capture_stderr=False, oneline=False,
Simon Glass3b3e3c02019-10-31 07:42:50 -060053 raise_on_error=True, cwd=None, binary=False, **kwargs):
Simon Glass0d24de92012-01-14 15:12:45 +000054 """
55 Perform a command pipeline, with optional input/output filenames.
56
Simon Glassa10fd932012-12-15 10:42:04 +000057 Args:
58 pipe_list: List of command lines to execute. Each command line is
59 piped into the next, and is itself a list of strings. For
60 example [ ['ls', '.git'] ['wc'] ] will pipe the output of
61 'ls .git' into 'wc'.
62 infile: File to provide stdin to the pipeline
63 outfile: File to store stdout
64 capture: True to capture output
65 capture_stderr: True to capture stderr
66 oneline: True to strip newline chars from output
67 kwargs: Additional keyword arguments to cros_subprocess.Popen()
68 Returns:
69 CommandResult object
Simon Glass0d24de92012-01-14 15:12:45 +000070 """
Simon Glass82012dd2014-09-05 19:00:12 -060071 if test_result:
72 if hasattr(test_result, '__call__'):
Simon Glass2b19321e2018-07-17 13:25:42 -060073 result = test_result(pipe_list=pipe_list)
74 if result:
75 return result
76 else:
77 return test_result
78 # No result: fall through to normal processing
Simon Glass3b3e3c02019-10-31 07:42:50 -060079 result = CommandResult(b'', b'', b'')
Simon Glass0d24de92012-01-14 15:12:45 +000080 last_pipe = None
Simon Glassa10fd932012-12-15 10:42:04 +000081 pipeline = list(pipe_list)
Simon Glassdc191502012-12-15 10:42:05 +000082 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
Simon Glassddaf5c82014-09-05 19:00:09 -060083 kwargs['stdout'] = None
84 kwargs['stderr'] = None
Simon Glass0d24de92012-01-14 15:12:45 +000085 while pipeline:
86 cmd = pipeline.pop(0)
Simon Glass0d24de92012-01-14 15:12:45 +000087 if last_pipe is not None:
88 kwargs['stdin'] = last_pipe.stdout
89 elif infile:
90 kwargs['stdin'] = open(infile, 'rb')
91 if pipeline or capture:
Simon Glassa10fd932012-12-15 10:42:04 +000092 kwargs['stdout'] = cros_subprocess.PIPE
Simon Glass0d24de92012-01-14 15:12:45 +000093 elif outfile:
94 kwargs['stdout'] = open(outfile, 'wb')
Simon Glassa10fd932012-12-15 10:42:04 +000095 if capture_stderr:
96 kwargs['stderr'] = cros_subprocess.PIPE
Simon Glass0d24de92012-01-14 15:12:45 +000097
Simon Glassa10fd932012-12-15 10:42:04 +000098 try:
99 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
Paul Burtonac3fde92016-09-27 16:03:51 +0100100 except Exception as err:
Simon Glassa10fd932012-12-15 10:42:04 +0000101 result.exception = err
Simon Glassdc191502012-12-15 10:42:05 +0000102 if raise_on_error:
103 raise Exception("Error running '%s': %s" % (user_pipestr, str))
104 result.return_code = 255
Simon Glass3b3e3c02019-10-31 07:42:50 -0600105 return result.ToOutput(binary)
Simon Glass0d24de92012-01-14 15:12:45 +0000106
107 if capture:
Simon Glassa10fd932012-12-15 10:42:04 +0000108 result.stdout, result.stderr, result.combined = (
109 last_pipe.CommunicateFilter(None))
110 if result.stdout and oneline:
Simon Glass3b3e3c02019-10-31 07:42:50 -0600111 result.output = result.stdout.rstrip(b'\r\n')
Simon Glassa10fd932012-12-15 10:42:04 +0000112 result.return_code = last_pipe.wait()
Simon Glass0d24de92012-01-14 15:12:45 +0000113 else:
Simon Glassa10fd932012-12-15 10:42:04 +0000114 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
Simon Glassdc191502012-12-15 10:42:05 +0000115 if raise_on_error and result.return_code:
116 raise Exception("Error running '%s'" % user_pipestr)
Simon Glass3b3e3c02019-10-31 07:42:50 -0600117 return result.ToOutput(binary)
Simon Glass0d24de92012-01-14 15:12:45 +0000118
Simon Glass785f1542016-07-25 18:59:00 -0600119def Output(*cmd, **kwargs):
Simon Glass512f4552019-07-08 13:18:23 -0600120 kwargs['raise_on_error'] = kwargs.get('raise_on_error', True)
121 return RunPipe([cmd], capture=True, **kwargs).stdout
Simon Glass0d24de92012-01-14 15:12:45 +0000122
Simon Glassa10fd932012-12-15 10:42:04 +0000123def OutputOneLine(*cmd, **kwargs):
Simon Glass3b3e3c02019-10-31 07:42:50 -0600124 """Run a command and output it as a single-line string
125
126 The command us expected to produce a single line of output
127
128 Returns:
129 String containing output of command
130 """
Simon Glassdc191502012-12-15 10:42:05 +0000131 raise_on_error = kwargs.pop('raise_on_error', True)
Simon Glass3b3e3c02019-10-31 07:42:50 -0600132 result = RunPipe([cmd], capture=True, oneline=True,
133 raise_on_error=raise_on_error, **kwargs).stdout.strip()
134 return result
Simon Glass0d24de92012-01-14 15:12:45 +0000135
136def Run(*cmd, **kwargs):
Simon Glassa10fd932012-12-15 10:42:04 +0000137 return RunPipe([cmd], **kwargs).stdout
Simon Glass0d24de92012-01-14 15:12:45 +0000138
139def RunList(cmd):
Simon Glassa10fd932012-12-15 10:42:04 +0000140 return RunPipe([cmd], capture=True).stdout
141
142def StopAll():
143 cros_subprocess.stay_alive = False