/
core.go
92 lines (84 loc) · 1.9 KB
/
core.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
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"strings"
)
// prompts
const (
PromptEntry = "Valar Morghulis\nType 'exit' at any time to quit the shell."
PromptExit = "Valar Dohaeris"
)
// built-ins
const (
CommandExit = "exit"
CommandChangeDir = "cd"
)
// currentCmd is set by 'handleCommand' and is leveraged by the signal handler
// to determine whether the signal should be propagated to a subprocess or
// the foreground shell.
// I don't love this shared state approach, so may rethink it.
var currentCmd *exec.Cmd = nil
func signalHandler(sigChan <-chan os.Signal) {
for {
sig := <-sigChan
if currentCmd != nil { // kill the currently executing subprocess
currentCmd.Process.Signal(sig)
} else { // kill the foreground
os.Exit(1)
}
}
}
func handleCommand(s string) error {
parts := strings.Split(s, " ")
switch parts[0] {
case "":
return nil
case CommandChangeDir:
err := os.Chdir(parts[1])
return err
default:
cmd := exec.Command(parts[0], parts[1:]...)
currentCmd = cmd
out, err := cmd.Output()
currentCmd = nil
if err != nil {
return err
}
fmt.Printf(string(out))
return nil
}
}
var icon = string([]byte{0xF0, 0x9F, 0x92, 0x80})
var commandFlag = flag.String("c", "", "Run a command in a shell subprocess and then exit")
func main() {
flag.Parse()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt)
go signalHandler(sigChan)
if *commandFlag != "" {
handleCommand(*commandFlag)
} else {
reader := bufio.NewReader(os.Stdin)
fmt.Println(PromptEntry)
for {
fmt.Printf("%s ", icon)
raw, err := reader.ReadString('\n')
text := strings.TrimRight(raw, "\n")
if err == io.EOF || text == CommandExit {
fmt.Println(PromptExit)
os.Exit(0)
}
err = handleCommand(text)
if err != nil {
// debug-only fmt.Println(err)
fmt.Printf("can't process command: %s\n", text)
}
}
}
}