shell_manager.hh (2290B)
1 #ifndef shell_manager_hh_INCLUDED 2 #define shell_manager_hh_INCLUDED 3 4 #include "array_view.hh" 5 #include "env_vars.hh" 6 #include "string.hh" 7 #include "utils.hh" 8 #include "unique_descriptor.hh" 9 #include "completion.hh" 10 11 #include <signal.h> 12 #include <sys/wait.h> 13 #include <unistd.h> 14 15 namespace Kakoune 16 { 17 18 class Context; 19 20 struct ShellContext 21 { 22 ConstArrayView<String> params; 23 EnvVarMap env_vars; 24 }; 25 26 struct EnvVarDesc 27 { 28 using Retriever = Vector<String> (*)(StringView name, const Context&); 29 30 StringView str; 31 bool prefix; 32 Retriever func; 33 }; 34 35 inline void closepid(int pid){ kill(pid, SIGTERM); int status = 0; waitpid(pid, &status, 0); } 36 37 using UniqueFd = UniqueDescriptor<::close>; 38 using UniquePid = UniqueDescriptor<closepid>; 39 40 struct Shell 41 { 42 UniquePid pid; 43 UniqueFd in; 44 UniqueFd out; 45 UniqueFd err; 46 }; 47 48 class ShellManager : public Singleton<ShellManager> 49 { 50 public: 51 ShellManager(ConstArrayView<EnvVarDesc> builtin_env_vars); 52 53 enum class Flags 54 { 55 None = 0, 56 WaitForStdout = 1 57 }; 58 friend constexpr bool with_bit_ops(Meta::Type<Flags>) { return true; } 59 60 std::pair<String, int> eval(StringView cmdline, const Context& context, 61 FunctionRef<StringView ()> stdin_generator, 62 Flags flags = Flags::WaitForStdout, 63 const ShellContext& shell_context = {}); 64 65 std::pair<String, int> eval(StringView cmdline, const Context& context, 66 StringView in, 67 Flags flags = Flags::WaitForStdout, 68 const ShellContext& shell_context = {}) 69 { 70 return eval(cmdline, context, 71 [in]() mutable { return std::exchange(in, StringView{}); }, 72 flags, shell_context); 73 } 74 75 Shell spawn(StringView cmdline, 76 const Context& context, 77 bool open_stdin, 78 const ShellContext& shell_context = {}); 79 80 Vector<String> get_val(StringView name, const Context& context) const; 81 82 CandidateList complete_env_var(StringView prefix, ByteCount cursor_pos) const; 83 84 private: 85 String m_shell; 86 87 ConstArrayView<EnvVarDesc> m_env_vars; 88 }; 89 90 } 91 92 #endif // shell_manager_hh_INCLUDED