This repository has been archived by the owner on Jun 28, 2023. It is now read-only.
/
shared.go
91 lines (82 loc) · 1.87 KB
/
shared.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
package shared
import (
"errors"
"fmt"
"io/ioutil"
"os/exec"
"path/filepath"
"runtime"
"golang.org/x/tools/go/packages"
)
const RootCmd = "gmlgo"
const gmlGoPackage = "github.com/silbinarywolf/gml-go"
var (
cmdDir string
cmdErr error
)
func computeCmdSourceDir(gameDir string) (string, error) {
currentDir, err := filepath.Abs(gameDir)
if err != nil {
return "", err
}
cfg := &packages.Config{
Dir: currentDir,
}
pkgs, err := packages.Load(cfg, "github.com/silbinarywolf/gml-go/cmd/gmlgo")
if err != nil {
return "", err
}
if len(pkgs) == 0 {
return "", errors.New("Unable to find package: " + gmlGoPackage)
}
pkg := pkgs[0]
if len(pkg.GoFiles) == 0 {
return "", errors.New("Cannot find *.go files in:" + currentDir)
}
dir := filepath.Dir(pkg.GoFiles[0])
return dir, nil
}
// OpenBrowsers open web browser with a given url
// (can be http:// or file://)
func OpenBrowser(url string) {
// Taken from:
// https://presstige.io/p/Using-Go-instead-of-bash-for-scripts-6b51885c1f6940aeb40476000d0eb0fc
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
if err != nil {
panic(err)
}
}
func ReadDefaultIndexHTML(gameDir string) ([]byte, error) {
dir, err := computeCmdSourceDir(gameDir)
if err != nil {
return nil, err
}
dir = dir + "/files/index.html"
data, err := ioutil.ReadFile(dir)
if err != nil {
return nil, err
}
return data, nil
}
func ReadDefaultWasmJS(gameDir string) ([]byte, error) {
dir, err := computeCmdSourceDir(gameDir)
if err != nil {
return nil, err
}
dir = dir + "/files/wasm_exec.js"
data, err := ioutil.ReadFile(dir)
if err != nil {
return nil, err
}
return data, nil
}