reso-execution/cmd/server/runtime.go

74 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-03-16 13:41:03 +00:00
package main
import (
2024-03-17 01:53:16 +00:00
"fmt"
2024-03-16 13:41:03 +00:00
"log"
"os/exec"
2024-03-16 15:15:31 +00:00
"path/filepath"
2024-03-16 13:41:03 +00:00
"strings"
// import file writer
"os"
// import websocket
)
2024-03-16 15:15:31 +00:00
func handleCase(caseName, data string) string {
2024-03-17 01:53:16 +00:00
caseName = strings.ReplaceAll(caseName, "\n", "")
caseName = strings.ReplaceAll(caseName, "\r", "")
2024-03-16 15:15:31 +00:00
caseName = strings.ReplaceAll(caseName, ":", "")
log.Println("Handling case", caseName)
2024-03-16 13:41:03 +00:00
switch caseName {
2024-03-16 15:15:31 +00:00
case "python", "python3", "py":
2024-03-17 01:53:16 +00:00
log.Println(data)
2024-03-16 15:15:31 +00:00
runPython(data)
2024-03-17 01:53:16 +00:00
default:
fmt.Printf("caseName: %q\n", caseName)
log.Println(data)
2024-03-16 13:41:03 +00:00
}
2024-03-16 15:15:31 +00:00
return ""
2024-03-16 13:41:03 +00:00
}
2024-03-16 15:15:31 +00:00
func runPython(data string) {
log.Println("Running python")
// create a file in the workspace directory
f, err := os.Create("./workspace/main.py")
2024-03-16 13:41:03 +00:00
if err != nil {
log.Println("Error creating file")
2024-03-16 15:15:31 +00:00
return
2024-03-16 13:41:03 +00:00
}
2024-03-16 15:15:31 +00:00
defer f.Close()
2024-03-16 13:41:03 +00:00
2024-03-16 15:15:31 +00:00
// write the data to the file
_, err = f.WriteString(data)
2024-03-16 13:41:03 +00:00
if err != nil {
2024-03-16 15:15:31 +00:00
log.Println("Error writing to file")
return
2024-03-16 13:41:03 +00:00
}
2024-03-16 15:15:31 +00:00
// find python, python3, or py in the system
2024-03-17 00:15:27 +00:00
fname, err := exec.LookPath("python3")
if err != nil {
log.Println("Python not found")
} else {
log.Println("Python found at", fname)
}
// fname := "C:\\Users\\zachd\\scoop\\shims\\python3.exe"
2024-03-16 13:41:03 +00:00
2024-03-16 15:15:31 +00:00
// if main.py does not exist, return
if _, err := os.Stat("./workspace/main.py"); os.IsNotExist(err) {
log.Println("File does not exist")
return
}
cmd := exec.Command(fname, "./main.py")
cmd.Dir = filepath.ToSlash("./workspace/")
2024-03-17 01:53:16 +00:00
cmd.Stdout = pyWriter
2024-03-16 15:15:31 +00:00
cmd.Stderr = pyWriter
// start the command
cmd.Run()
log.Println("Python runtime finished")
2024-03-16 13:41:03 +00:00
}