Skip to content

Commit e8b121b

Browse files
committed
[util] Add swift_build_support.shell.capture.
- This is an analog to `call`, which returns the captured output of the command.
1 parent 3d06dee commit e8b121b

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

utils/swift_build_support/swift_build_support/shell.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,13 @@ def _print_command(dry_run, command, env=None, prompt="+ "):
6060

6161

6262
def call(command, stderr=None, env=None, dry_run=None, print_command=True):
63+
"""
64+
call(command, ...) -> str
65+
66+
Execute the given command.
67+
68+
This function will raise an exception on any command failure.
69+
"""
6370
dry_run = _coerce_dry_run(dry_run)
6471
if dry_run or print_command:
6572
_print_command(dry_run, command, env=env)
@@ -81,6 +88,35 @@ def call(command, stderr=None, env=None, dry_run=None, print_command=True):
8188
"': " + e.strerror)
8289

8390

91+
def capture(command, stderr=None, env=None, dry_run=None, print_command=True):
92+
"""
93+
capture(command, ...) -> str
94+
95+
Execute the given command and return the standard output.
96+
97+
This function will raise an exception on any command failure.
98+
"""
99+
dry_run = _coerce_dry_run(dry_run)
100+
if dry_run or print_command:
101+
_print_command(dry_run, command, env=env)
102+
if dry_run:
103+
return
104+
_env = None
105+
if env is not None:
106+
_env = dict(os.environ)
107+
_env.update(env)
108+
try:
109+
return subprocess.check_output(command, env=_env, stderr=stderr)
110+
except subprocess.CalledProcessError as e:
111+
diagnostics.fatal(
112+
"command terminated with a non-zero exit status " +
113+
str(e.returncode) + ", aborting")
114+
except OSError as e:
115+
diagnostics.fatal(
116+
"could not execute '" + quote_command(command) +
117+
"': " + e.strerror)
118+
119+
84120
@contextmanager
85121
def pushd(path, dry_run=None, print_command=True):
86122
dry_run = _coerce_dry_run(dry_run)

utils/swift_build_support/tests/test_shell.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ def test_call(self):
6363
+ cp {foo_file} {bar_file}
6464
'''.format(foo_file=foo_file, bar_file=bar_file))
6565

66+
def test_capture(self):
67+
self.assertEqual(shell.capture(["echo", "hi"]), "hi\n")
68+
69+
with self.assertRaises(SystemExit):
70+
shell.capture(["false"])
71+
6672
def test_rmtree(self):
6773
shell.dry_run = False
6874
path = os.path.join(self.tmpdir, 'foo', 'bar')

0 commit comments

Comments
 (0)