From 0d1af1ad63dc615eab64008e046d683aa041b84b Mon Sep 17 00:00:00 2001 From: Liav A Date: Fri, 4 Nov 2022 11:50:40 +0200 Subject: [PATCH] LibCore: Add System::exec_command method This method was taken from the pls utility and its purpose is to execute a given command with all the required requirements such as providing a suitable exec environment. --- Userland/Libraries/LibCore/System.cpp | 23 +++++++++++++++++++++++ Userland/Libraries/LibCore/System.h | 5 +++++ 2 files changed, 28 insertions(+) diff --git a/Userland/Libraries/LibCore/System.cpp b/Userland/Libraries/LibCore/System.cpp index f060bb87c3..3490f33818 100644 --- a/Userland/Libraries/LibCore/System.cpp +++ b/Userland/Libraries/LibCore/System.cpp @@ -979,6 +979,29 @@ ErrorOr adjtime(const struct timeval* delta, struct timeval* old_delta) } #endif +#ifdef AK_OS_SERENITY +ErrorOr exec_command(Vector& command, bool preserve_env) +{ + Vector exec_environment; + for (size_t i = 0; environ[i]; ++i) { + StringView env_view { environ[i], strlen(environ[i]) }; + auto maybe_needle = env_view.find('='); + + if (!maybe_needle.has_value()) + continue; + + // FIXME: Allow a custom selection of variables once ArgsParser supports options with optional parameters. + if (!preserve_env && env_view.substring_view(0, maybe_needle.value()) != "TERM"sv) + continue; + + exec_environment.append(env_view); + } + + TRY(Core::System::exec(command.at(0), command, Core::System::SearchInPath::Yes, exec_environment)); + return {}; +} +#endif + ErrorOr exec(StringView filename, Span arguments, SearchInPath search_in_path, Optional> environment) { #ifdef AK_OS_SERENITY diff --git a/Userland/Libraries/LibCore/System.h b/Userland/Libraries/LibCore/System.h index 9b1b8345e0..d506dd8df0 100644 --- a/Userland/Libraries/LibCore/System.h +++ b/Userland/Libraries/LibCore/System.h @@ -165,6 +165,11 @@ enum class SearchInPath { No, Yes, }; + +#ifdef AK_OS_SERENITY +ErrorOr exec_command(Vector& command, bool preserve_env); +#endif + ErrorOr exec(StringView filename, Span arguments, SearchInPath, Optional> environment = {}); ErrorOr socket(int domain, int type, int protocol);