-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathodin.go
93 lines (73 loc) · 1.73 KB
/
odin.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
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"github.com/bwmarrin/discordgo"
)
var (
odinPath string
mainRegex *regexp.Regexp
osImportRegex *regexp.Regexp
)
func initOdin() {
odinPath, _ = exec.LookPath("odin")
mainRegex = regexp.MustCompile(mainRegexStr)
}
func odinRunHandle(session *discordgo.Session, msg *discordgo.MessageCreate) {
mesg := strings.TrimPrefix(msg.Content, "!odinrun")
mesg = strings.TrimSpace(mesg)
i1 := strings.Index(mesg, "```")
if i1 < 0 {
session.ChannelMessageSend(msg.ChannelID, "Please put your code in a code block")
return
}
offset := i1 + 3
i2 := strings.Index(mesg[offset:], "```")
if i2 < 0 {
session.ChannelMessageSend(msg.ChannelID, "Incomplete code block")
return
}
code := mesg[offset : i2+offset]
mainInCode := mainRegex.MatchString(code)
if mainInCode == false {
code = strings.ReplaceAll(odinProgramTemplate, "REPLACE_ME", code)
}
session.ChannelMessageSend(msg.ChannelID, "Running code...")
f, err := os.Create("test.odin")
defer os.Remove("test.odin")
if err != nil {
session.ChannelMessageSend(msg.ChannelID, "Couldn't create file to run!!")
return
}
w := bufio.NewWriter(f)
w.WriteString(code)
w.Flush()
f.Close()
var out bytes.Buffer
cmd := exec.Cmd{
Path: odinPath,
Args: []string{"odin", "run", "test.odin"},
Stdout: &out,
Stderr: &out,
}
cmd.Run()
resp := fmt.Sprintf("Output: ```\n%v\n```", out.String())
session.ChannelMessageSend(msg.ChannelID, resp)
}
const mainRegexStr = `main\s::\sproc\(\)\s{(?:(?:.|\n)*)}`
const odinProgramTemplate = `
package main
import "core:fmt"
import "core:math"
import "core:math/linalg"
import "core:mem"
import "core:strings"
main :: proc() {
REPLACE_ME;
}
`