-
Notifications
You must be signed in to change notification settings - Fork 0
/
psh.go
121 lines (104 loc) · 2.11 KB
/
psh.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
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/pglass/pshhh/ast"
"github.com/pglass/pshhh/exe"
"github.com/pglass/pshhh/lex"
)
type EnvVars []string
func (e *EnvVars) String() string {
return fmt.Sprint(*e)
}
func (e *EnvVars) Set(value string) error {
*e = append(*e, value)
return nil
}
var (
filename string
text string
debug bool
env_vars EnvVars
)
func init() {
flag.StringVar(&filename, "f", "", "The filename of a script to run")
flag.StringVar(&text, "t", "", "Execute the given text")
flag.BoolVar(&debug, "d", false, "Enable debug mode")
flag.Var(&env_vars, "e", "Preset environment variables")
}
func main() {
flag.Parse()
log.SetFlags(0)
if !debug {
log.SetOutput(ioutil.Discard)
}
var lexer *lex.Lexer = nil
if filename != "" {
if b, err := ioutil.ReadFile(filename); err != nil {
log.Fatal(err)
} else {
lexer = lex.NewLexer(string(b))
}
} else if text != "" {
lexer = lex.NewLexer(text)
}
if lexer != nil {
if err := run_single(lexer); err != nil {
handle_error(err, false)
}
} else {
run_shell()
}
}
func run_single(lexer *lex.Lexer) error {
parser := ast.NewParser(lexer)
root, err := parser.Parse()
if err != nil {
return fmt.Errorf("%v\n", err)
} else if root == nil {
return fmt.Errorf("Parse failure (got nil node)\n")
} else {
interpreter := exe.NewInterpreter()
interpreter.Env = env_vars
log.Printf("Environment:")
for _, item := range interpreter.Env {
log.Printf(" %v", item)
}
if err := interpreter.Interpret(root); err != nil {
return err
}
}
return nil
}
func run_shell() {
for {
fmt.Print("$ ")
reader := bufio.NewReader(os.Stdin)
if input, err := reader.ReadString('\n'); err != nil {
log.Fatalf("error: %v\n", err)
} else {
lexer := lex.NewLexer(strings.TrimSpace(input))
if err := run_single(lexer); err != nil {
handle_error(err, true)
}
}
}
}
func handle_error(err error, is_shell bool) {
fmt.Print(err)
switch e := err.(type) {
case exe.ExitError:
if !is_shell {
os.Exit(e.ExitCode)
}
default:
if !is_shell {
os.Exit(1)
}
}
}