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
|
package shell
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"src.elv.sh/pkg/cli"
"src.elv.sh/pkg/cli/term"
"src.elv.sh/pkg/daemon/daemondefs"
"src.elv.sh/pkg/diag"
"src.elv.sh/pkg/edit"
"src.elv.sh/pkg/eval"
"src.elv.sh/pkg/mods/daemon"
"src.elv.sh/pkg/mods/store"
"src.elv.sh/pkg/parse"
"src.elv.sh/pkg/strutil"
"src.elv.sh/pkg/sys"
"src.elv.sh/pkg/ui"
)
// 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
// Configuration for the interactive mode.
type interactCfg struct {
RC string
ActivateDaemon daemondefs.ActivateFunc
SpawnConfig *daemondefs.SpawnConfig
}
// Interface satisfied by the line editor. Used for swapping out the editor with
// minEditor when necessary.
type editor interface {
ReadCode() (string, error)
RunAfterCommandHooks(src parse.Source, duration float64, err error)
}
// Runs an interactive shell session.
func interact(ev *eval.Evaler, fds [3]*os.File, cfg *interactCfg) {
if interactiveRescueShell {
defer handlePanic()
}
var daemonClient daemondefs.Client
if cfg.ActivateDaemon != nil && cfg.SpawnConfig != nil {
// TODO(xiaq): Connect to daemon and install daemon module
// asynchronously.
cl, err := cfg.ActivateDaemon(fds[2], cfg.SpawnConfig)
if err != nil {
fmt.Fprintln(fds[2], "Cannot connect to daemon:", err)
fmt.Fprintln(fds[2], "Daemon-related functions will likely not work.")
}
if cl != nil {
// Even if error is not nil, we install daemon-related
// functionalities anyway. Daemon may eventually come online and
// become functional.
daemonClient = cl
ev.PreExitHooks = append(ev.PreExitHooks, func() { cl.Close() })
ev.AddModule("store", store.Ns(cl))
ev.AddModule("daemon", daemon.Ns(cl))
}
}
// Build Editor.
var ed editor
if sys.IsATTY(fds[0].Fd()) {
restoreTTY := term.SetupForTUIOnce(fds[0], fds[1])
defer restoreTTY()
newed := edit.NewEditor(cli.NewTTY(fds[0], fds[2]), ev, daemonClient)
ev.ExtendBuiltin(eval.BuildNs().AddNs("edit", newed))
ev.BgJobNotify = func(s string) { newed.Notify(ui.T(s)) }
ed = newed
} else {
ed = newMinEditor(fds[0], fds[2])
}
// Source rc.elv.
if cfg.RC != "" {
err := sourceRC(fds, ev, ed, cfg.RC)
if err != nil {
diag.ShowError(fds[2], err)
}
}
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
// Execute the command line only if it is not entirely whitespace. This keeps side-effects,
// such as executing `$edit:after-command` hooks, from occurring when we didn't actually
// evaluate any code entered by the user.
if strings.TrimSpace(line) == "" {
continue
}
err = evalInTTY(fds, ev, ed,
parse.Source{Name: fmt.Sprintf("[tty %v]", cmdNum), Code: line})
if err != nil {
diag.ShowError(fds[2], err)
}
}
}
// 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())
}
}
func sourceRC(fds [3]*os.File, ev *eval.Evaler, ed editor, 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
}
return evalInTTY(fds, ev, ed, parse.Source{Name: absPath, Code: code, IsFile: true})
}
type minEditor struct {
in *bufio.Reader
out io.Writer
}
func newMinEditor(in, out *os.File) *minEditor {
return &minEditor{bufio.NewReader(in), out}
}
func (ed *minEditor) RunAfterCommandHooks(src parse.Source, duration float64, err error) {
// no-op; minEditor doesn't support this hook.
}
func (ed *minEditor) ReadCode() (string, error) {
wd, err := os.Getwd()
if err != nil {
wd = "?"
}
fmt.Fprintf(ed.out, "%s> ", wd)
line, err := ed.in.ReadString('\n')
return strutil.ChopLineEnding(line), err
}
|