forked from elves/elvish
/
interact.go
179 lines (162 loc) · 4.29 KB
/
interact.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
package shell
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/xiaq/persistent/hashmap"
"src.elv.sh/pkg/cli"
"src.elv.sh/pkg/cli/term"
"src.elv.sh/pkg/diag"
"src.elv.sh/pkg/edit"
"src.elv.sh/pkg/eval"
"src.elv.sh/pkg/eval/vals"
"src.elv.sh/pkg/eval/vars"
"src.elv.sh/pkg/parse"
"src.elv.sh/pkg/prog"
"src.elv.sh/pkg/sys"
)
// InteractiveRescueShell determines whether a panic results in a rescue shell
// being launched. It should be set to false by interactive mode unit tests.
var interactiveRescueShell bool = true
// InteractConfig keeps configuration for the interactive mode.
type InteractConfig struct {
SpawnDaemon bool
Paths Paths
}
// Interactive mode panic handler.
func handlePanic() {
r := recover()
if r != nil {
println()
print(sys.DumpStack())
println()
fmt.Println(r)
println("\nExecing recovery shell /bin/sh")
syscall.Exec("/bin/sh", []string{"/bin/sh"}, os.Environ())
}
}
// Interact runs an interactive shell session.
func Interact(fds [3]*os.File, cfg *InteractConfig) {
if interactiveRescueShell {
defer handlePanic()
}
ev, cleanup := setupShell(fds, cfg.Paths, cfg.SpawnDaemon)
defer cleanup()
// Build Editor.
var ed editor
if sys.IsATTY(fds[0]) {
newed := edit.NewEditor(cli.NewTTY(fds[0], fds[2]), ev, ev.DaemonClient())
ev.AddBuiltin(eval.NsBuilder{}.AddNs("edit", newed.Ns()).Ns())
ed = newed
} else {
ed = newMinEditor(fds[0], fds[2])
}
// Source rc.elv.
if cfg.Paths.Rc != "" {
err := sourceRC(fds, ev, cfg.Paths.Rc)
if err != nil {
diag.ShowError(fds[2], err)
}
}
term.Sanitize(fds[0], fds[2])
cooldown := time.Second
cmdNum := 0
for {
cmdNum++
line, err := ed.ReadCode()
if err == io.EOF {
break
} else if err != nil {
fmt.Fprintln(fds[2], "Editor error:", err)
if _, isMinEditor := ed.(*minEditor); !isMinEditor {
fmt.Fprintln(fds[2], "Falling back to basic line editor")
ed = newMinEditor(fds[0], fds[2])
} else {
fmt.Fprintln(fds[2], "Don't know what to do, pid is", os.Getpid())
fmt.Fprintln(fds[2], "Restarting editor in", cooldown)
time.Sleep(cooldown)
if cooldown < time.Minute {
cooldown *= 2
}
}
continue
}
// No error; reset cooldown.
cooldown = time.Second
// We only bother evaluating the statement(s) if the line is not entirely whitespace. This
// isn't especially important but keeps things like the `edit:command:-duration` variable
// from being updated when we didn't actually evaluate any statements.
if strings.TrimSpace(line) == "" {
continue
}
duration, err := evalInTTY(ev, fds,
parse.Source{Name: fmt.Sprintf("[tty %v]", cmdNum), Code: line})
edit.CommandDuration = duration
term.Sanitize(fds[0], fds[2])
if err != nil {
diag.ShowError(fds[2], err)
}
}
}
func sourceRC(fds [3]*os.File, ev *eval.Evaler, rcPath string) error {
absPath, err := filepath.Abs(rcPath)
if err != nil {
return fmt.Errorf("cannot get full path of rc.elv: %v", err)
}
code, err := readFileUTF8(absPath)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
duration, err := evalInTTY(ev, fds, parse.Source{Name: absPath, Code: code, IsFile: true})
edit.CommandDuration = duration
if err != nil {
return err
}
extraGlobal := extractExports(ev.Global(), fds[2])
if extraGlobal != nil {
ev.AddGlobal(extraGlobal)
}
return nil
}
const exportsVarName = "-exports-"
// If the namespace contains a variable named exportsVarName, extract its values
// into a namespace.
func extractExports(ns *eval.Ns, stderr io.Writer) *eval.Ns {
value, ok := ns.Index(exportsVarName)
if !ok {
return nil
}
if prog.DeprecationLevel >= 15 {
fmt.Fprintln(stderr,
"the $-exports- mechanism is deprecated; use edit:add-vars instead.")
}
exports, ok := value.(hashmap.Map)
if !ok {
fmt.Fprintf(stderr, "$%s is not map, ignored\n", exportsVarName)
return nil
}
nb := eval.NsBuilder{}
for it := exports.Iterator(); it.HasElem(); it.Next() {
k, v := it.Elem()
name, ok := k.(string)
if !ok {
fmt.Fprintf(stderr, "$%s[%s] is not string, ignored\n",
exportsVarName, vals.Repr(k, vals.NoPretty))
continue
}
if ns.HasName(name) {
fmt.Fprintf(stderr, "$%s already exists, ignored $%s[%s]\n",
name, exportsVarName, name)
continue
}
nb.Add(name, vars.FromInit(v))
}
return nb.Ns()
}