-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
109 lines (90 loc) · 2.4 KB
/
main.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
package main
import (
"flag"
"fmt"
"os"
"github.com/Syuparn/pangaea/envs"
"github.com/Syuparn/pangaea/object"
"github.com/Syuparn/pangaea/runscript"
)
var (
oneLiner = flag.String("e", "", "run one-line script")
jargon = flag.Bool("j", false, fmt.Sprintf("read jargon script saved in $%s (`~/.jargon.pangaea` by default)", envs.JargonFileKey))
readsLines = flag.Bool("n", false, "assign stdin each line to \\")
readsAndWritesLines = flag.Bool("p", false, "similar to -n but also print to evaluated values")
version = flag.Bool("v", false, "show version")
testCmdSet = flag.NewFlagSet("test", flag.ExitOnError)
)
// TODO: refactor handling of each options (by DDD or something else?)
func main() {
// test mode
if len(os.Args) >= 2 && os.Args[1] == "test" {
testCmdSet.Parse(os.Args[2:])
if path := testCmdSet.Arg(0); path != "" {
exitCode := runTest(path)
os.Exit(exitCode)
}
}
// normal mode
flag.Parse()
// show version
if *version {
showVersion()
os.Exit(0)
}
src := ""
if *jargon {
src = readJargon()
}
// run one-liner
if *oneLiner != "" {
src += wrapSource(*oneLiner, *readsLines, *readsAndWritesLines)
exitCode := run(src, object.StrFileName)
os.Exit(exitCode)
}
if srcFileName := flag.Arg(0); srcFileName != "" {
fileSrc, exitCode := runscript.ReadFile(srcFileName)
if exitCode != 0 {
os.Exit(exitCode)
}
src += fileSrc
exitCode = run(src, srcFileName)
os.Exit(exitCode)
}
runRepl(src)
}
func runTest(path string) int {
exitCode := runscript.RunTest(path, os.Stdin, os.Stdout)
return exitCode
}
func run(src string, fileName string) int {
exitCode := runscript.RunSource(src, fileName, os.Stdin, os.Stdout)
return exitCode
}
func runRepl(src string) {
runscript.StartREPL(src, os.Stdin, os.Stdout)
}
func showVersion() {
fmt.Println(runscript.Version)
}
func wrapSource(original string, readsLines, readsAndWritesLines bool) string {
if readsAndWritesLines {
return fmt.Sprintf(runscript.ReadStdinLinesAndWritesTemplate, original)
}
if readsLines {
return fmt.Sprintf(runscript.ReadStdinLinesTemplate, original)
}
return original
}
func readJargon() string {
fileName := envs.DefaultJargonFile()
if n, ok := os.LookupEnv(envs.JargonFileKey); ok {
fileName = n
}
bytes, err := os.ReadFile(fileName)
// error does not matter
if err != nil {
return ""
}
return string(bytes) + "\n"
}