forked from alfredxing/calc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (67 loc) · 1.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
package main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
)
import (
"github.com/alfredxing/calc/compute"
)
import (
"golang.org/x/crypto/ssh/terminal"
)
// Stores the state of the terminal before making it raw
var regularState *terminal.State
func main() {
if len(os.Args) > 1 {
input := strings.Replace(strings.Join(os.Args[1:], ""), " ", "", -1)
res, err := compute.Evaluate(input)
if err != nil {
return
}
fmt.Printf("%s\n", strconv.FormatFloat(res, 'G', -1, 64))
return
}
var err error
regularState, err = terminal.MakeRaw(0)
if err != nil {
panic(err)
}
defer terminal.Restore(0, regularState)
term := terminal.NewTerminal(os.Stdin, "> ")
term.AutoCompleteCallback = handleKey
for {
text, err := term.ReadLine()
if err != nil {
if err == io.EOF {
// Quit without error on Ctrl^D
exit()
}
panic(err)
}
text = strings.Replace(text, " ", "", -1)
if text == "exit" || text == "quit" {
break
}
res, err := compute.Evaluate(text)
if err != nil {
term.Write([]byte(fmt.Sprintln("Error: " + err.Error())))
continue
}
term.Write([]byte(fmt.Sprintln(strconv.FormatFloat(res, 'G', -1, 64))))
}
}
func handleKey(line string, pos int, key rune) (newLine string, newPos int, ok bool) {
if key == '\x03' {
// Quit without error on Ctrl^C
exit()
}
return "", 0, false
}
func exit() {
terminal.Restore(0, regularState)
fmt.Println()
os.Exit(0)
}