rust_shell/
shell_command.rs

1// Copyright 2017 Google Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use shell_child::ShellChild;
16use result::ShellResult;
17use result::ShellError;
18use std::process::Command;
19use std::process::Stdio;
20
21pub struct ShellCommand {
22    line: String,
23    pub command: Command,
24}
25
26impl ShellCommand {
27    pub fn new(line: String, command: Command) -> ShellCommand {
28        ShellCommand {
29            line: line,
30            command: command,
31        }
32    }
33
34    pub fn run(self) -> ShellResult {
35        self.spawn().and_then(|job| job.wait())
36    }
37
38    pub fn spawn(self) -> Result<ShellChild, ShellError> {
39        ShellChild::new(self.line, self.command)
40    }
41
42    pub fn stdout_utf8(mut self) -> Result<String, ShellError> {
43        self.command.stdout(Stdio::piped());
44        self.spawn()?.stdout_utf8()
45    }
46}
47
48#[test]
49fn test_shell_command() {
50    assert!(cmd!("test 1 = 1").run().is_ok());
51    assert!(cmd!("test 1 = 0").run().is_err());
52}
53
54#[test]
55fn test_shell_command_output() {
56    assert_eq!(&String::from_utf8_lossy(
57        &cmd!("echo Test").command.output().unwrap().stdout), "Test\n");
58    assert_eq!(cmd!("echo Test").stdout_utf8().unwrap(), "Test\n");
59}