1 // Copyright (c) 2024 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "gn/invoke_python.h"
6
7 #include "base/command_line.h"
8 #include "base/files/file_path.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "gn/build_settings.h"
11 #include "gn/err.h"
12 #include "gn/exec_process.h"
13 #include "gn/filesystem_utils.h"
14
15 namespace internal {
16
InvokePython(const BuildSettings * build_settings,const base::FilePath & python_script_path,const std::string & python_script_extra_args,const base::FilePath & output_path,bool quiet,Err * err)17 bool InvokePython(const BuildSettings* build_settings,
18 const base::FilePath& python_script_path,
19 const std::string& python_script_extra_args,
20 const base::FilePath& output_path,
21 bool quiet,
22 Err* err) {
23 const base::FilePath& python_path = build_settings->python_path();
24 base::CommandLine cmdline(python_path);
25 cmdline.AppendArg("--");
26 cmdline.AppendArgPath(python_script_path);
27 cmdline.AppendArgPath(output_path);
28 if (!python_script_extra_args.empty()) {
29 cmdline.AppendArg(python_script_extra_args);
30 }
31 base::FilePath startup_dir =
32 build_settings->GetFullPath(build_settings->build_dir());
33
34 std::string output;
35 std::string stderr_output;
36
37 int exit_code = 0;
38 if (!internal::ExecProcess(cmdline, startup_dir, &output, &stderr_output,
39 &exit_code)) {
40 *err =
41 Err(Location(), "Could not execute python.",
42 "I was trying to execute \"" + FilePathToUTF8(python_path) + "\".");
43 return false;
44 }
45
46 if (!quiet) {
47 printf("%s", output.c_str());
48 fprintf(stderr, "%s", stderr_output.c_str());
49 }
50
51 if (exit_code != 0) {
52 *err = Err(Location(), "Python has quit with exit code " +
53 base::IntToString(exit_code) + ".");
54 return false;
55 }
56
57 return true;
58 }
59
60 } // namespace internal
61