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_commands.go
257 lines (238 loc) · 6.29 KB
/
execute_commands.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package compiler
import (
"errors"
"flag"
"fmt"
"io"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"time"
)
func (c *Command) execute_cd() error {
switch len(c.Arguments) {
case 0:
home, err := os.UserHomeDir()
if err != nil {
return errors.Join(errors.New("cd: failed to get home directory"), err)
}
return os.Chdir(home)
case 1:
path := c.Arguments[0]
if strings.HasPrefix(path, "~") {
if home, err := os.UserHomeDir(); err == nil {
path = filepath.Join(home, path[1:])
} else {
return errors.Join(errors.New("cd: failed to get home directory"), err)
}
}
return os.Chdir(path)
default:
_, _ = fmt.Fprintln(**c.Stderr, "cd: too many arguments")
return errors.New("cd: too many arguments")
}
}
func (c *Command) execute_exit() error {
switch len(c.Arguments) {
case 0:
os.Exit(0)
case 1:
code, err := strconv.Atoi(c.Arguments[0])
if err != nil {
_, _ = fmt.Fprintln(**c.Stderr, "exit: ", err)
return errors.Join(fmt.Errorf("exit: failed to parse argument %q as an integer", c.Arguments[0]), err)
}
os.Exit(code)
default:
_, _ = fmt.Fprintln(**c.Stderr, "exit: too many arguments")
return errors.New("exit: too many arguments")
}
return nil
}
func (c *Command) execute_echo() error {
_, _ = fmt.Fprintln(**c.Stdout, strings.Join(c.Arguments, " "))
return nil
}
func (c *Command) execute_cat() error {
if len(c.Arguments) > 0 {
// for each argument, open the file and copy its contents to stdout
for _, arg := range c.Arguments {
if f, err := os.Open(arg); err == nil {
if _, err := io.Copy(**c.Stdout, f); err != nil {
_, _ = fmt.Fprintln(**c.Stderr, "cat: ", err)
return errors.Join(fmt.Errorf("cat: failed to copy file %q", arg), err)
}
f.Close()
} else {
_, _ = fmt.Fprintln(**c.Stderr, "cat: ", err)
return errors.Join(fmt.Errorf("cat: failed to open file %q", arg), err)
}
}
} else {
r := io.TeeReader(**c.Stdin, **c.Stdout)
// read from r until EOF
for {
buf := make([]byte, 1024)
_, err := r.Read(buf)
if err != nil {
if err == io.EOF {
break
}
_, _ = fmt.Fprintln(**c.Stderr, "cat: ", err)
return errors.Join(errors.New("cat: failed to read from stdin"), err)
}
}
}
return nil
}
func (c *Command) execute_export() error {
if len(c.Arguments) > 0 {
for _, arg := range c.Arguments {
pair := os.ExpandEnv(arg)
if pair != "" {
kv := strings.Split(pair, "=")
if len(kv) >= 2 {
os.Setenv(kv[0], strings.Join(kv[1:], "="))
} else {
// does this variable exist?
if _, ok := os.LookupEnv(kv[0]); !ok {
// if not, set it to an empty string
os.Setenv(kv[0], "")
}
}
}
}
} else {
for _, env := range os.Environ() {
_, _ = fmt.Fprintf(**c.Stdout, "declare -x %s\n", env)
}
}
return nil
}
func (c *Command) execute_unset() error {
if len(c.Arguments) > 0 {
for _, arg := range c.Arguments {
os.Unsetenv(arg)
}
}
return nil
}
func (c *Command) execute_whoami() error {
if u, err := user.Current(); err == nil {
_, _ = fmt.Fprintln(**c.Stdout, u.Username)
} else {
_, _ = fmt.Fprintln(**c.Stderr, "whoami: ", err)
return errors.Join(errors.New("whoami: failed to get current user"), err)
}
return nil
}
func (c *Command) execute_pwd() error {
if wd, err := os.Getwd(); err == nil {
_, _ = fmt.Fprintln(**c.Stdout, wd)
} else {
_, _ = fmt.Fprintln(**c.Stderr, "pwd: ", err)
return errors.Join(errors.New("pwd: failed to get working directory"), err)
}
return nil
}
func findExecutable(name string, all bool) []string {
pathList := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator))
foundBinaries := []string{}
for _, path := range pathList {
exe := filepath.Join(path, name)
if exe, is := isExecutable(exe); is {
foundBinaries = append(foundBinaries, exe)
if !all {
break
}
}
}
return foundBinaries
}
func (c *Command) execute_type() error {
if len(c.Arguments) != 0 {
for _, arg := range c.Arguments {
if _, ok := builtinCommands[arg]; ok {
_, _ = fmt.Fprintf(**c.Stdout, "%s is a builtin\n", arg)
continue
}
foundBinaries := findExecutable(arg, false)
if len(foundBinaries) != 0 {
_, _ = fmt.Fprintf(**c.Stdout, "%s is %s\n", arg, foundBinaries[0])
} else {
_, _ = fmt.Fprintf(**c.Stderr, "type: could not find %s\n", arg)
}
}
} else {
_, _ = fmt.Fprintln(**c.Stderr, "type: missing arguments")
return errors.New("type: missing arguments")
}
return nil
}
func (c *Command) execute_which() error {
if len(c.Arguments) != 0 {
fs := flag.NewFlagSet("which", flag.ContinueOnError)
fs.SetOutput(**c.Stderr)
all := fs.Bool("a", false, "List all instances of executables found (instead of just the first one).")
silent := fs.Bool("s", false, "Do not print anything, only return an exit status.")
if err := fs.Parse(c.Arguments); err != nil {
return errors.Join(fmt.Errorf("which: failed to parse arguments %q", c.Arguments), err)
}
for _, arg := range fs.Args() {
foundBinaries := findExecutable(arg, *all)
if len(foundBinaries) != 0 {
if !*silent {
for _, exe := range foundBinaries {
_, _ = fmt.Fprintln(**c.Stdout, exe)
}
}
} else {
return fmt.Errorf("which: %s not found", arg)
}
}
} else {
_, _ = fmt.Fprintln(**c.Stderr, "which: missing arguments")
return errors.New("which: missing arguments")
}
return nil
}
func (c *Command) execute_yes() error {
if len(c.Arguments) == 0 {
for {
_, _ = fmt.Fprintln(**c.Stdout, "y")
<-time.After(200 * time.Millisecond)
}
} else {
for {
_, _ = fmt.Fprintln(**c.Stdout, strings.Join(c.Arguments, " "))
<-time.After(200 * time.Millisecond)
}
}
}
func (c *Command) execute_true() error {
return nil
}
func (c *Command) execute_false() error {
return errors.New("false")
}
func (c *Command) execute_sleep() error {
if len(c.Arguments) == 0 {
return errors.New("sleep: missing operand")
}
if len(c.Arguments) > 1 {
return errors.New("sleep: too many arguments")
}
d, err := time.ParseDuration(c.Arguments[0])
if err != nil {
// try to parse the duration as a float
if f, err := strconv.ParseFloat(c.Arguments[0], 64); err == nil {
d = time.Duration(f * float64(time.Second))
} else {
return errors.Join(fmt.Errorf("sleep: failed to parse argument %q as a duration", c.Arguments[0]), err)
}
}
<-time.After(d)
return nil
}