xref: /rk3399_rockchip-uboot/tools/patman/command.py (revision dc191505b903220a8581303efef0a1ead0e06532)
10d24de9dSSimon Glass# Copyright (c) 2011 The Chromium OS Authors.
20d24de9dSSimon Glass#
30d24de9dSSimon Glass# See file CREDITS for list of people who contributed to this
40d24de9dSSimon Glass# project.
50d24de9dSSimon Glass#
60d24de9dSSimon Glass# This program is free software; you can redistribute it and/or
70d24de9dSSimon Glass# modify it under the terms of the GNU General Public License as
80d24de9dSSimon Glass# published by the Free Software Foundation; either version 2 of
90d24de9dSSimon Glass# the License, or (at your option) any later version.
100d24de9dSSimon Glass#
110d24de9dSSimon Glass# This program is distributed in the hope that it will be useful,
120d24de9dSSimon Glass# but WITHOUT ANY WARRANTY; without even the implied warranty of
130d24de9dSSimon Glass# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
140d24de9dSSimon Glass# GNU General Public License for more details.
150d24de9dSSimon Glass#
160d24de9dSSimon Glass# You should have received a copy of the GNU General Public License
170d24de9dSSimon Glass# along with this program; if not, write to the Free Software
180d24de9dSSimon Glass# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
190d24de9dSSimon Glass# MA 02111-1307 USA
200d24de9dSSimon Glass#
210d24de9dSSimon Glass
220d24de9dSSimon Glassimport os
23a10fd93cSSimon Glassimport cros_subprocess
240d24de9dSSimon Glass
250d24de9dSSimon Glass"""Shell command ease-ups for Python."""
260d24de9dSSimon Glass
27a10fd93cSSimon Glassclass CommandResult:
28a10fd93cSSimon Glass    """A class which captures the result of executing a command.
29a10fd93cSSimon Glass
30a10fd93cSSimon Glass    Members:
31a10fd93cSSimon Glass        stdout: stdout obtained from command, as a string
32a10fd93cSSimon Glass        stderr: stderr obtained from command, as a string
33a10fd93cSSimon Glass        return_code: Return code from command
34a10fd93cSSimon Glass        exception: Exception received, or None if all ok
35a10fd93cSSimon Glass    """
36a10fd93cSSimon Glass    def __init__(self):
37a10fd93cSSimon Glass        self.stdout = None
38a10fd93cSSimon Glass        self.stderr = None
39a10fd93cSSimon Glass        self.return_code = None
40a10fd93cSSimon Glass        self.exception = None
41a10fd93cSSimon Glass
42a10fd93cSSimon Glass
43a10fd93cSSimon Glassdef RunPipe(pipe_list, infile=None, outfile=None,
44a10fd93cSSimon Glass            capture=False, capture_stderr=False, oneline=False,
45*dc191505SSimon Glass            raise_on_error=True, cwd=None, **kwargs):
460d24de9dSSimon Glass    """
470d24de9dSSimon Glass    Perform a command pipeline, with optional input/output filenames.
480d24de9dSSimon Glass
49a10fd93cSSimon Glass    Args:
50a10fd93cSSimon Glass        pipe_list: List of command lines to execute. Each command line is
51a10fd93cSSimon Glass            piped into the next, and is itself a list of strings. For
52a10fd93cSSimon Glass            example [ ['ls', '.git'] ['wc'] ] will pipe the output of
53a10fd93cSSimon Glass            'ls .git' into 'wc'.
54a10fd93cSSimon Glass        infile: File to provide stdin to the pipeline
55a10fd93cSSimon Glass        outfile: File to store stdout
56a10fd93cSSimon Glass        capture: True to capture output
57a10fd93cSSimon Glass        capture_stderr: True to capture stderr
58a10fd93cSSimon Glass        oneline: True to strip newline chars from output
59a10fd93cSSimon Glass        kwargs: Additional keyword arguments to cros_subprocess.Popen()
60a10fd93cSSimon Glass    Returns:
61a10fd93cSSimon Glass        CommandResult object
620d24de9dSSimon Glass    """
63a10fd93cSSimon Glass    result = CommandResult()
640d24de9dSSimon Glass    last_pipe = None
65a10fd93cSSimon Glass    pipeline = list(pipe_list)
66*dc191505SSimon Glass    user_pipestr =  '|'.join([' '.join(pipe) for pipe in pipe_list])
670d24de9dSSimon Glass    while pipeline:
680d24de9dSSimon Glass        cmd = pipeline.pop(0)
690d24de9dSSimon Glass        if last_pipe is not None:
700d24de9dSSimon Glass            kwargs['stdin'] = last_pipe.stdout
710d24de9dSSimon Glass        elif infile:
720d24de9dSSimon Glass            kwargs['stdin'] = open(infile, 'rb')
730d24de9dSSimon Glass        if pipeline or capture:
74a10fd93cSSimon Glass            kwargs['stdout'] = cros_subprocess.PIPE
750d24de9dSSimon Glass        elif outfile:
760d24de9dSSimon Glass            kwargs['stdout'] = open(outfile, 'wb')
77a10fd93cSSimon Glass        if capture_stderr:
78a10fd93cSSimon Glass            kwargs['stderr'] = cros_subprocess.PIPE
790d24de9dSSimon Glass
80a10fd93cSSimon Glass        try:
81a10fd93cSSimon Glass            last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
82a10fd93cSSimon Glass        except Exception, err:
83a10fd93cSSimon Glass            result.exception = err
84*dc191505SSimon Glass            if raise_on_error:
85*dc191505SSimon Glass                raise Exception("Error running '%s': %s" % (user_pipestr, str))
86*dc191505SSimon Glass            result.return_code = 255
87*dc191505SSimon Glass            return result
880d24de9dSSimon Glass
890d24de9dSSimon Glass    if capture:
90a10fd93cSSimon Glass        result.stdout, result.stderr, result.combined = (
91a10fd93cSSimon Glass                last_pipe.CommunicateFilter(None))
92a10fd93cSSimon Glass        if result.stdout and oneline:
93a10fd93cSSimon Glass            result.output = result.stdout.rstrip('\r\n')
94a10fd93cSSimon Glass        result.return_code = last_pipe.wait()
950d24de9dSSimon Glass    else:
96a10fd93cSSimon Glass        result.return_code = os.waitpid(last_pipe.pid, 0)[1]
97*dc191505SSimon Glass    if raise_on_error and result.return_code:
98*dc191505SSimon Glass        raise Exception("Error running '%s'" % user_pipestr)
99a10fd93cSSimon Glass    return result
1000d24de9dSSimon Glass
1010d24de9dSSimon Glassdef Output(*cmd):
102*dc191505SSimon Glass    return RunPipe([cmd], capture=True, raise_on_error=False).stdout
1030d24de9dSSimon Glass
104a10fd93cSSimon Glassdef OutputOneLine(*cmd, **kwargs):
105*dc191505SSimon Glass    raise_on_error = kwargs.pop('raise_on_error', True)
106a10fd93cSSimon Glass    return (RunPipe([cmd], capture=True, oneline=True,
107*dc191505SSimon Glass            raise_on_error=raise_on_error,
108a10fd93cSSimon Glass            **kwargs).stdout.strip())
1090d24de9dSSimon Glass
1100d24de9dSSimon Glassdef Run(*cmd, **kwargs):
111a10fd93cSSimon Glass    return RunPipe([cmd], **kwargs).stdout
1120d24de9dSSimon Glass
1130d24de9dSSimon Glassdef RunList(cmd):
114a10fd93cSSimon Glass    return RunPipe([cmd], capture=True).stdout
115a10fd93cSSimon Glass
116a10fd93cSSimon Glassdef StopAll():
117a10fd93cSSimon Glass    cros_subprocess.stay_alive = False
118