This repository has been archived by the owner on Jul 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
execute.go
103 lines (90 loc) · 2.17 KB
/
execute.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package compiler
import (
"errors"
"fmt"
"strings"
"sync"
)
func Execute(text string, iop *ioProvider) error {
tokens, err := LexicalAnalysis(text, iop)
if err != nil {
return errors.Join(errors.New("failed to lexically analyze input"), err)
}
commands, err := Parse(text, tokens, iop)
if err != nil {
return errors.Join(errors.New("failed to parse input"), err)
}
wg := sync.WaitGroup{}
for i, command := range commands {
if command.Background {
wg.Add(1)
go func() {
defer wg.Done()
err := command.Execute()
stdout := **command.Stdout
_ = stdout.Close()
stderr := **command.Stderr
_ = stderr.Close()
iop.Close()
if err != nil {
err = errors.Join(fmt.Errorf("failed to execute command %d: %q", i, command.String()), err)
_, _ = fmt.Fprintln(iop.DefaultErr, err)
}
}()
} else {
err := command.Execute()
iop.Close()
stdout := **command.Stdout
_ = stdout.Close()
stderr := **command.Stderr
_ = stderr.Close()
if err != nil {
return errors.Join(fmt.Errorf("failed to execute command %d: %q", i, command.String()), err)
}
}
}
wg.Wait()
return nil
}
var builtinCommands map[string]func(*Command) error
func init() {
builtinCommands = map[string]func(*Command) error{
"cd": (*Command).execute_cd,
"exit": (*Command).execute_exit,
"echo": (*Command).execute_echo,
"cat": (*Command).execute_cat,
"export": (*Command).execute_export,
"unset": (*Command).execute_unset,
"whoami": (*Command).execute_whoami,
"pwd": (*Command).execute_pwd,
"which": (*Command).execute_which,
"type": (*Command).execute_type,
"sudo": (*Command).execute_sudo,
"yes": (*Command).execute_yes,
"true": (*Command).execute_true,
"false": (*Command).execute_false,
"sleep": (*Command).execute_sleep,
}
}
func (c *Command) Execute() error {
var err error
if fn, builtin := builtinCommands[strings.ToLower(c.Executable)]; builtin {
err = fn(c)
} else {
err = c.execute_default()
}
if err != nil {
// failed
if c.Or != nil {
return c.Or.Execute()
} else {
return err
}
} else {
// succeeded
if c.And != nil {
return c.And.Execute()
}
}
return nil
}