blob: 24358784f26c459ef4a468a31c2ad36be7e886f9 [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass26132882012-01-14 15:12:45 +00002# Copyright (c) 2011 The Chromium OS Authors.
3#
Simon Glass26132882012-01-14 15:12:45 +00004
5import os
Simon Glassa997ea52020-04-17 18:09:04 -06006
7from patman import cros_subprocess
Simon Glass26132882012-01-14 15:12:45 +00008
9"""Shell command ease-ups for Python."""
10
Simon Glass34e59432012-12-15 10:42:04 +000011class CommandResult:
12 """A class which captures the result of executing a command.
13
14 Members:
15 stdout: stdout obtained from command, as a string
16 stderr: stderr obtained from command, as a string
17 return_code: Return code from command
18 exception: Exception received, or None if all ok
19 """
20 def __init__(self):
21 self.stdout = None
22 self.stderr = None
Simon Glassde384972014-09-05 19:00:12 -060023 self.combined = None
Simon Glass34e59432012-12-15 10:42:04 +000024 self.return_code = None
25 self.exception = None
26
Simon Glassde384972014-09-05 19:00:12 -060027 def __init__(self, stdout='', stderr='', combined='', return_code=0,
28 exception=None):
29 self.stdout = stdout
30 self.stderr = stderr
31 self.combined = combined
32 self.return_code = return_code
33 self.exception = exception
34
Simon Glass840be732022-01-29 14:14:05 -070035 def to_output(self, binary):
Simon Glasscc311ac2019-10-31 07:42:50 -060036 if not binary:
Simon Glass4ba3ea52020-06-07 06:45:46 -060037 self.stdout = self.stdout.decode('utf-8')
38 self.stderr = self.stderr.decode('utf-8')
39 self.combined = self.combined.decode('utf-8')
Simon Glasscc311ac2019-10-31 07:42:50 -060040 return self
41
Simon Glassde384972014-09-05 19:00:12 -060042
43# This permits interception of RunPipe for test purposes. If it is set to
44# a function, then that function is called with the pipe list being
45# executed. Otherwise, it is assumed to be a CommandResult object, and is
Simon Glass840be732022-01-29 14:14:05 -070046# returned as the result for every run_pipe() call.
Simon Glassde384972014-09-05 19:00:12 -060047# When this value is None, commands are executed as normal.
48test_result = None
Simon Glass34e59432012-12-15 10:42:04 +000049
Simon Glass840be732022-01-29 14:14:05 -070050def run_pipe(pipe_list, infile=None, outfile=None,
Simon Glass34e59432012-12-15 10:42:04 +000051 capture=False, capture_stderr=False, oneline=False,
Simon Glass146b6022021-10-19 21:43:24 -060052 raise_on_error=True, cwd=None, binary=False,
53 output_func=None, **kwargs):
Simon Glass26132882012-01-14 15:12:45 +000054 """
55 Perform a command pipeline, with optional input/output filenames.
56
Simon Glass34e59432012-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
Simon Glass146b6022021-10-19 21:43:24 -060067 output_func: Output function to call with each output fragment
68 (if it returns True the function terminates)
Simon Glass34e59432012-12-15 10:42:04 +000069 kwargs: Additional keyword arguments to cros_subprocess.Popen()
70 Returns:
71 CommandResult object
Simon Glass26132882012-01-14 15:12:45 +000072 """
Simon Glassde384972014-09-05 19:00:12 -060073 if test_result:
74 if hasattr(test_result, '__call__'):
Simon Glass6a8480b2018-07-17 13:25:42 -060075 result = test_result(pipe_list=pipe_list)
76 if result:
77 return result
78 else:
79 return test_result
80 # No result: fall through to normal processing
Simon Glasscc311ac2019-10-31 07:42:50 -060081 result = CommandResult(b'', b'', b'')
Simon Glass26132882012-01-14 15:12:45 +000082 last_pipe = None
Simon Glass34e59432012-12-15 10:42:04 +000083 pipeline = list(pipe_list)
Simon Glass519fad22012-12-15 10:42:05 +000084 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
Simon Glassf1bf6862014-09-05 19:00:09 -060085 kwargs['stdout'] = None
86 kwargs['stderr'] = None
Simon Glass26132882012-01-14 15:12:45 +000087 while pipeline:
88 cmd = pipeline.pop(0)
Simon Glass26132882012-01-14 15:12:45 +000089 if last_pipe is not None:
90 kwargs['stdin'] = last_pipe.stdout
91 elif infile:
92 kwargs['stdin'] = open(infile, 'rb')
93 if pipeline or capture:
Simon Glass34e59432012-12-15 10:42:04 +000094 kwargs['stdout'] = cros_subprocess.PIPE
Simon Glass26132882012-01-14 15:12:45 +000095 elif outfile:
96 kwargs['stdout'] = open(outfile, 'wb')
Simon Glass34e59432012-12-15 10:42:04 +000097 if capture_stderr:
98 kwargs['stderr'] = cros_subprocess.PIPE
Simon Glass26132882012-01-14 15:12:45 +000099
Simon Glass34e59432012-12-15 10:42:04 +0000100 try:
101 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
Paul Burtonf14a1312016-09-27 16:03:51 +0100102 except Exception as err:
Simon Glass34e59432012-12-15 10:42:04 +0000103 result.exception = err
Simon Glass519fad22012-12-15 10:42:05 +0000104 if raise_on_error:
105 raise Exception("Error running '%s': %s" % (user_pipestr, str))
106 result.return_code = 255
Simon Glass840be732022-01-29 14:14:05 -0700107 return result.to_output(binary)
Simon Glass26132882012-01-14 15:12:45 +0000108
109 if capture:
Simon Glass34e59432012-12-15 10:42:04 +0000110 result.stdout, result.stderr, result.combined = (
Simon Glass4c0557b2022-01-29 14:14:08 -0700111 last_pipe.communicate_filter(output_func))
Simon Glass34e59432012-12-15 10:42:04 +0000112 if result.stdout and oneline:
Simon Glasscc311ac2019-10-31 07:42:50 -0600113 result.output = result.stdout.rstrip(b'\r\n')
Simon Glass34e59432012-12-15 10:42:04 +0000114 result.return_code = last_pipe.wait()
Simon Glass26132882012-01-14 15:12:45 +0000115 else:
Simon Glass34e59432012-12-15 10:42:04 +0000116 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
Simon Glass519fad22012-12-15 10:42:05 +0000117 if raise_on_error and result.return_code:
118 raise Exception("Error running '%s'" % user_pipestr)
Simon Glass840be732022-01-29 14:14:05 -0700119 return result.to_output(binary)
Simon Glass26132882012-01-14 15:12:45 +0000120
Simon Glass840be732022-01-29 14:14:05 -0700121def output(*cmd, **kwargs):
Simon Glass097483d2019-07-08 13:18:23 -0600122 kwargs['raise_on_error'] = kwargs.get('raise_on_error', True)
Simon Glass840be732022-01-29 14:14:05 -0700123 return run_pipe([cmd], capture=True, **kwargs).stdout
Simon Glass26132882012-01-14 15:12:45 +0000124
Simon Glass840be732022-01-29 14:14:05 -0700125def output_one_line(*cmd, **kwargs):
Simon Glasscc311ac2019-10-31 07:42:50 -0600126 """Run a command and output it as a single-line string
127
128 The command us expected to produce a single line of output
129
130 Returns:
131 String containing output of command
132 """
Simon Glass519fad22012-12-15 10:42:05 +0000133 raise_on_error = kwargs.pop('raise_on_error', True)
Simon Glass840be732022-01-29 14:14:05 -0700134 result = run_pipe([cmd], capture=True, oneline=True,
Simon Glasscc311ac2019-10-31 07:42:50 -0600135 raise_on_error=raise_on_error, **kwargs).stdout.strip()
136 return result
Simon Glass26132882012-01-14 15:12:45 +0000137
Simon Glass840be732022-01-29 14:14:05 -0700138def run(*cmd, **kwargs):
139 return run_pipe([cmd], **kwargs).stdout
Simon Glass26132882012-01-14 15:12:45 +0000140
Simon Glass840be732022-01-29 14:14:05 -0700141def run_list(cmd):
142 return run_pipe([cmd], capture=True).stdout
Simon Glass34e59432012-12-15 10:42:04 +0000143
Simon Glass840be732022-01-29 14:14:05 -0700144def stop_all():
Simon Glass34e59432012-12-15 10:42:04 +0000145 cros_subprocess.stay_alive = False