-
Notifications
You must be signed in to change notification settings - Fork 2
/
builtins.go
120 lines (106 loc) · 2.17 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
package goash
import (
"context"
"errors"
"fmt"
"os"
"strconv"
)
type BuiltinHandler func(context.Context, []string) error
var (
Builtins map[string]BuiltinHandler
currentDir = ""
)
func init() {
Builtins = map[string]BuiltinHandler{
"cd": cd,
"exit": exit,
"env": env,
"getenv": getenv,
"setenv": setenv,
"unsetenv": unsetenv,
// "fork": fork,
"refresh": refresh,
}
}
func homedir() string {
homedir := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if homedir == "" {
homedir = os.Getenv("USERPROFILE")
}
if homedir == "" {
homedir = os.Getenv("HOME")
}
return homedir
}
func refresh(ctx context.Context, call []string) error {
readLine.Clean()
return nil
}
func cd(ctx context.Context, call []string) error {
var dst string
if len(call) == 1 {
dst = homedir()
} else if call[1] == "~" && len(call) == 2 {
dst = homedir()
} else {
dst = call[1]
}
if err := os.Chdir(dst); err != nil {
return err
}
currentDir = dst
if readLine != nil {
readLine.SetPrompt(getPrompt())
}
return nil
}
func exit(ctx context.Context, call []string) (err error) {
code := 0
if len(call) >= 2 {
code, err = strconv.Atoi(call[1])
if err != nil {
return err
}
}
os.Exit(code)
return nil
}
func env(ctx context.Context, call []string) error {
for _, envvar := range os.Environ() {
fmt.Println(envvar)
}
return nil
}
func getenv(ctx context.Context, call []string) error {
if len(call) != 2 {
return errors.New("`getenv <variable name>`")
}
fmt.Println(os.Getenv(call[1]))
return nil
}
func setenv(ctx context.Context, call []string) error {
if len(call) != 3 {
return errors.New("`setenv <variable name> <value>`")
}
return os.Setenv(call[1], call[2])
}
func unsetenv(ctx context.Context, call []string) error {
if len(call) != 2 {
return errors.New("`unsetenv <variable name>`")
}
return os.Setenv(call[1], "")
}
func fork(ctx context.Context, call []string) error {
if len(call) < 2 {
return errors.New("`fork <command...>`")
}
go func(ctx context.Context, call []string) {
cmd, err := buildCommand(ctx, call)
if err != nil || cmd == nil {
return
}
cmd.Start()
}(ctx, call)
return nil
}