summaryrefslogtreecommitdiff
path: root/src/shell_manager.hh
blob: f6ef38a4409229d67f83441803ccecdf7cfec669 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#ifndef shell_manager_hh_INCLUDED
#define shell_manager_hh_INCLUDED

#include "array_view.hh"
#include "env_vars.hh"
#include "string.hh"
#include "utils.hh"
#include "unique_descriptor.hh"
#include "completion.hh"

#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>

namespace Kakoune
{

class Context;

struct ShellContext
{
    ConstArrayView<String> params;
    EnvVarMap env_vars;
};

struct EnvVarDesc
{
    using Retriever = Vector<String> (*)(StringView name, const Context&);

    StringView str;
    bool prefix;
    Retriever func;
};

inline void closepid(int pid){ kill(pid, SIGTERM); int status = 0; waitpid(pid, &status, 0); }

using UniqueFd = UniqueDescriptor<::close>;
using UniquePid = UniqueDescriptor<closepid>;

struct Shell
{
    UniquePid pid;
    UniqueFd in;
    UniqueFd out;
    UniqueFd err;
};

class ShellManager : public Singleton<ShellManager>
{
public:
    ShellManager(ConstArrayView<EnvVarDesc> builtin_env_vars);

    enum class Flags
    {
        None = 0,
        WaitForStdout = 1
    };
    friend constexpr bool with_bit_ops(Meta::Type<Flags>) { return true; }

    std::pair<String, int> eval(StringView cmdline, const Context& context,
                                StringView input = {},
                                Flags flags = Flags::WaitForStdout,
                                const ShellContext& shell_context = {});

    Shell spawn(StringView cmdline,
                const Context& context,
                bool open_stdin,
                const ShellContext& shell_context = {});

    Vector<String> get_val(StringView name, const Context& context) const;

    CandidateList complete_env_var(StringView prefix, ByteCount cursor_pos) const;

private:
    String m_shell;

    ConstArrayView<EnvVarDesc> m_env_vars;
};

}

#endif // shell_manager_hh_INCLUDED