/
shell.go
120 lines (111 loc) · 2.4 KB
/
shell.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 shellgo
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"github.com/chzyer/readline"
)
var env *Env
func doExec(conf *Config, slice []string) {
if slice[0] == "exit" {
os.Exit(0)
}
env.ErrMesg = ""
cmd, ok := env.BuiltinCmd[slice[0]]
if !ok {
if conf.UseSysCmd {
cmd := exec.Command(slice[0], slice[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
env.ErrMesg = err.Error()
}
} else {
env.ErrMesg = "1"
fmt.Printf("shell-go: %s: command not fond\n", slice[0])
}
return
}
env.cid, _, _ = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if env.cid == 0 {
ioutil.WriteFile(fmt.Sprintf("%s/%d.out", os.TempDir(), os.Getpid()), []byte(cmd.Call(slice[1:])), 0600)
os.Exit(0)
} else {
var ws syscall.WaitStatus
syscall.Wait4(int(env.cid), &ws, 0, nil)
filename := fmt.Sprintf("%s/%d.out", os.TempDir(), env.cid)
data, err := ioutil.ReadFile(filename)
if err == nil {
os.Remove(filename)
env.ErrMesg = string(data)
}
env.cid = 0
}
}
type completer struct{}
func (c *completer) Do(line []rune, pos int) (newLine [][]rune, length int) {
length = pos
for k, cmd := range env.BuiltinCmd {
if strings.Index(string(line), k+" ") == 0 {
s := []rune(strings.TrimLeft(string(line[len(k+" "):]), " "))
newLine, l := cmd.AutoComplete(s, len(s))
return newLine, pos + l
}
if string(line) == k {
return [][]rune{[]rune(" ")}, pos
}
if n := strings.Index(k, string(line)); n == 0 {
newLine = append(newLine, []rune(k[pos:]+" "))
}
}
return
}
func Run(conf Config) {
signal.Notify(env.interrupt, os.Interrupt)
go func() {
for {
<-env.interrupt
if env.cid != 0 {
syscall.Kill(int(env.cid), syscall.SIGKILL)
}
}
}()
r, err := readline.NewEx(&readline.Config{
InterruptPrompt: "^C",
EOFPrompt: "exit",
HistorySearchFold: true,
AutoComplete: &completer{},
})
if err != nil {
panic(err)
}
for {
r.SetPrompt(conf.Prompt.String())
if line, err := r.Readline(); err != nil {
if err != readline.ErrInterrupt {
os.Exit(0)
} else {
select {
case env.interrupt <- os.Kill:
default:
}
}
} else {
var slice []string
for _, s := range strings.Split(line, " ") {
if s != "" {
slice = append(slice, s)
}
}
if len(slice) == 0 {
continue
}
doExec(&conf, slice)
}
}
}