postup_commands.cpp
1 // SPDX-FileCopyrightText: Copyright (C) 2024-2025 Marek Küthe <m.k@mk16.de> 2 // 3 // SPDX-License-Identifier: GPL-3.0-or-later 4 5 #include "postup_commands.hpp" 6 7 void PostupCommands::add_postup_command(const std::string& command) 8 { 9 this->_postup_commands.push_back(command); 10 } 11 12 #ifdef BOOST_PROCESS_V1 13 14 void PostupCommands::execute_commands() const 15 { 16 for (const auto& postup_command : this->_postup_commands) 17 { 18 BOOST_LOG_TRIVIAL(debug) 19 << "Execute post up command: " << postup_command << std::endl; 20 std::error_code ec; 21 boost::process::v1::child child( 22 postup_command, 23 boost::process::v1::std_out > boost::process::v1::null, 24 boost::process::v1::std_err > boost::process::v1::null, 25 ec); 26 child.wait(); 27 BOOST_LOG_TRIVIAL(debug) 28 << "Post up command result: " << child.exit_code() << std::endl; 29 if (child.exit_code() != 0 || ec) 30 { 31 if (ec) 32 { 33 BOOST_LOG_TRIVIAL(fatal) 34 << "Failed to execute post up command: " << ec.message() 35 << std::endl; 36 } 37 throw std::runtime_error("Failed to execute post up command."); 38 } 39 } 40 } 41 42 #else 43 44 void PostupCommands::execute_commands( 45 const boost::asio::any_io_executor ex) const 46 { 47 for (const auto& postup_command : this->_postup_commands) 48 { 49 BOOST_LOG_TRIVIAL(debug) 50 << "Execute post up command: " << postup_command << std::endl; 51 const boost::process::shell postup_shell(postup_command); 52 const auto postup_command_args = std::span( 53 postup_shell.argv(), static_cast<std::size_t>(postup_shell.argc())); 54 55 if (postup_command_args.empty()) 56 { 57 throw std::runtime_error("Failed to execute post up command since " 58 "there is no command to execute."); 59 } 60 61 const std::string_view exe(postup_command_args.at(0)); 62 const bool is_path_to_file = exe.contains('/'); 63 64 boost::process::process child( 65 ex, 66 (is_path_to_file ? exe : postup_shell.exe()), 67 postup_shell.args(), 68 boost::process::process_stdio{ 69 .in = nullptr, .out = nullptr, .err = nullptr}); 70 boost::system::error_code ec; 71 child.wait(ec); 72 BOOST_LOG_TRIVIAL(debug) 73 << "Post up command result: " << child.exit_code() << std::endl; 74 if (child.exit_code() != 0 || ec) 75 { 76 if (ec) 77 { 78 BOOST_LOG_TRIVIAL(fatal) 79 << "Failed to execute post up command: " << ec.message() 80 << std::endl; 81 } 82 throw std::runtime_error("Failed to execute post up command."); 83 } 84 } 85 } 86 87 #endif