-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builtins.go
354 lines (321 loc) · 6.82 KB
/
builtins.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package hush
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"strconv"
"strings"
"syscall"
"time"
"github.com/fatih/color"
"github.com/johnstarich/go/datasize"
"github.com/pkg/errors"
)
type builtinFunc func(term console, args ...string) error
var (
builtins = map[string]builtinFunc{}
)
func init() {
for k, v := range map[string]builtinFunc{
"cat": cat,
"cd": cd,
"chmod": chmod,
"clear": clear,
"echo": echo,
"env": env,
"exit": exit,
"ls": ls,
"mkdir": mkdir,
"mv": mv,
"pwd": pwd,
"rm": rm,
"rmdir": rmdir,
"touch": touch,
"which": which,
} {
builtins[k] = v
}
}
func echo(term console, args ...string) error {
fmt.Fprintln(term.Stdout(), strings.Join(args, " "))
return nil
}
func pwd(term console, args ...string) error {
path, err := os.Getwd()
if err != nil {
return err
}
fmt.Fprintln(term.Stdout(), path)
return nil
}
func ls(term console, args ...string) error {
set := flag.NewFlagSet("ls", flag.ContinueOnError)
longForm := set.Bool("l", false, "Long format")
err := set.Parse(args)
if err != nil {
if err == flag.ErrHelp {
return nil
}
return err
}
args = set.Args()
if len(args) == 0 {
args = []string{"."}
}
if len(args) == 1 {
return printFileNames(term, args[0], *longForm)
}
for _, f := range args {
fmt.Fprintln(term.Stdout(), f+":")
err := printFileNames(term, f, *longForm)
if err != nil {
return err
}
fmt.Fprintln(term.Stdout())
}
return nil
}
func printFileNames(term console, dir string, longForm bool) error {
infos, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
if !longForm {
for _, info := range infos {
fmt.Fprintln(term.Stdout(), info.Name())
}
return nil
}
var t table
t.Align(leftAlign, rightAlign)
for _, info := range infos {
value, units := formatBytes(datasize.Bytes(info.Size()))
t.Add(info.Mode(), value, units, info.ModTime().Format(time.Stamp), info.Name())
}
fmt.Fprint(term.Stdout(), t)
return nil
}
func formatBytes(b datasize.Size) (string, string) {
value, unit := b.FormatSI()
return strings.TrimSuffix(fmt.Sprintf("%.1f", value), ".0"), unit
}
func cd(term console, args ...string) error {
switch len(args) {
case 0:
dir, err := os.UserHomeDir()
if err != nil {
return err
}
args = []string{dir}
fallthrough
case 1:
dir := args[0]
info, err := os.Stat(dir)
if err != nil {
return err
}
if !info.IsDir() {
return errors.Errorf("Not a directory: %s", dir)
}
return os.Chdir(dir)
default:
return errors.New("Too many args")
}
}
func mkdir(term console, args ...string) error {
switch len(args) {
case 0:
return errors.New("Must provide a path to create a directory")
default:
for _, dir := range args {
err := os.Mkdir(dir, 0755)
if err != nil {
return err
}
}
return nil
}
}
func cat(term console, args ...string) error {
if len(args) == 0 {
_, err := io.Copy(term.Stdout(), getconsoleStdin(term))
return err
}
for _, path := range args {
if info, err := os.Stat(path); err == nil && info.IsDir() {
return errors.Errorf("%s: Is a directory", path)
}
f, err := os.Open(path)
if err != nil {
return err
}
_, err = io.Copy(term.Stdout(), f)
if err != nil {
return err
}
}
return nil
}
func mv(term console, args ...string) error {
switch len(args) {
case 0, 1:
return errors.New("Not enough args")
case 2:
src := args[0]
dest := args[1]
if strings.HasSuffix(dest, "/") {
dest += path.Base(src)
}
return os.Rename(src, dest)
default:
return errors.New("Too many args")
}
}
func rm(term console, args ...string) error {
set := flag.NewFlagSet("rm", flag.ContinueOnError)
recursive := set.Bool("r", false, "Remove recursively")
if err := set.Parse(args); err != nil {
return err
}
if set.NArg() == 0 {
return errors.New("Not enough args")
}
rmFunc := os.RemoveAll
if !*recursive {
rmFunc = func(path string) error {
info, err := os.Stat(path)
if err != nil {
return err
}
if info.IsDir() {
return &os.PathError{Path: path, Op: "remove", Err: syscall.EISDIR}
}
return os.Remove(path)
}
}
for _, f := range set.Args() {
err := rmFunc(f)
if err != nil {
return err
}
}
return nil
}
func rmdir(term console, args ...string) error {
if len(args) == 0 {
return errors.New("Not enough args")
}
for _, path := range args {
info, err := os.Stat(path)
if err != nil {
return err
}
if !info.IsDir() {
return &os.PathError{Path: path, Op: "remove", Err: syscall.ENOTDIR}
}
err = os.Remove(path)
if err != nil {
return err
}
}
return nil
}
func touch(term console, args ...string) error {
if len(args) == 0 {
return errors.New("Not enough args")
}
now := time.Now()
for _, path := range args {
err := os.Chtimes(path, now, now)
if err != nil && !os.IsNotExist(err) {
return err
}
if os.IsNotExist(err) {
f, err := os.Create(path)
if err != nil {
return err
}
err = f.Close()
if err != nil {
return err
}
}
}
return nil
}
func which(term console, args ...string) error {
if len(args) == 0 {
return errors.New("Not enough args")
}
for _, arg := range args {
path, err := exec.LookPath(arg)
if err != nil {
return err
}
fmt.Fprintln(term.Stdout(), path)
}
return nil
}
func clear(term console, args ...string) error {
term.(*terminal).Clear()
return nil
}
func exit(term console, args ...string) error {
if len(args) == 0 {
return &exitErr{Code: 0}
}
exitCode, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return err
}
fmt.Fprintf(term.Stderr(), color.RedString("Exited with code %d\n"), exitCode)
return &exitErr{Code: int(exitCode)}
}
func env(term console, args ...string) error {
var kv []string
const equals = '='
for i, arg := range args {
if !strings.ContainsRune(arg, equals) {
args = args[i:]
break
}
kv = append(kv, arg)
}
if len(args) == 0 {
for _, e := range os.Environ() {
fmt.Fprintln(term.Stdout(), e)
}
return nil
}
return runWithEnv(term, kv, args...)
}
func splitKeyValue(kv string) (key, value string) {
const equals = "="
tokens := strings.SplitN(kv, equals, 2)
if len(tokens) < 2 {
return strings.Join(tokens, equals), ""
}
return tokens[0], strings.Join(tokens[1:], equals)
}
func runWithEnv(term console, env []string, args ...string) error {
cmd := exec.Command(args[0], args[1:]...) // nolint:gosec // Running any given process args is the whole point, so this isn't a security issue.
cmd.Stdout = term.Stdout()
cmd.Stderr = term.Stderr()
cmd.Env = append(os.Environ(), env...)
return runCmd(cmd, cmdOptions{})
}
func chmod(term console, args ...string) error {
if len(args) < 2 {
return errors.New("Not enough args")
}
perm, err := strconv.ParseInt(args[0], 8, 12) // parse octal permission
if err != nil {
return err
}
file := args[1]
return os.Chmod(file, os.FileMode(perm))
}