1 //
2 // Copyright (C) 2023 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 #include "host/commands/cvd/unittests/server/cmd_runner.h"
17
18 #include <android-base/strings.h>
19
20 namespace cuttlefish {
21
CmdResult(const std::string & stdout_str,const std::string & stderr_str,const int ret_code)22 CmdResult::CmdResult(const std::string& stdout_str,
23 const std::string& stderr_str, const int ret_code)
24 : stdout_{stdout_str}, stderr_{stderr_str}, code_{ret_code} {}
25
Run(const cvd_common::Args & args,const cvd_common::Envs & envs)26 CmdResult CmdRunner::Run(const cvd_common::Args& args,
27 const cvd_common::Envs& envs) {
28 if (args.empty() || args.front().empty()) {
29 return CmdResult("", "Empty or invalid command", -1);
30 }
31 const auto& cmd = args.front();
32 cvd_common::Args cmd_args{args.begin() + 1, args.end()};
33 CmdRunner cmd_runner(Command(cmd), cmd_args, envs);
34 return cmd_runner.Run();
35 }
36
Run(const std::string & args,const cvd_common::Envs & envs)37 CmdResult CmdRunner::Run(const std::string& args,
38 const cvd_common::Envs& envs) {
39 return CmdRunner::Run(android::base::Tokenize(args, " "), envs);
40 }
41
CmdRunner(Command && cmd,const cvd_common::Args & args,const cvd_common::Envs & envs)42 CmdRunner::CmdRunner(Command&& cmd, const cvd_common::Args& args,
43 const cvd_common::Envs& envs)
44 : cmd_(std::move(cmd)) {
45 for (const auto& arg : args) {
46 cmd_.AddParameter(arg);
47 }
48 for (const auto& [key, value] : envs) {
49 cmd_.AddEnvironmentVariable(key, value);
50 }
51 }
52
Run()53 CmdResult CmdRunner::Run() {
54 std::string stdout_str;
55 std::string stderr_str;
56 auto ret_code =
57 RunWithManagedStdio(std::move(cmd_), nullptr, std::addressof(stdout_str),
58 std::addressof(stderr_str));
59 return CmdResult(stdout_str, stderr_str, ret_code);
60 }
61
62 } // namespace cuttlefish
63