forked from scakemyer/quasar
-
Notifications
You must be signed in to change notification settings - Fork 43
/
build_shared.go
103 lines (78 loc) · 1.54 KB
/
build_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
92
93
94
95
96
97
98
99
100
101
102
103
//go:build shared
package main
import (
"C"
"bufio"
"fmt"
"os"
"time"
"github.com/elgatito/elementum/exit"
)
var (
readFile *os.File
writeFile *os.File
)
func initShared() {
exit.Reset()
exit.IsShared = true
}
func initLog(arg string) {
logPath = arg
originalStdout := os.Stdout
readFile, writeFile, _ = os.Pipe()
os.Stdout = writeFile
os.Stderr = writeFile
go func() {
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
if err != nil {
fmt.Printf("Could not open log file '%s' for writing: %s\n", logPath, err)
return
}
defer logFile.Close()
os.Stdout.WriteString(fmt.Sprintf("Redirecting Stdout/Stderr to %s\r\n", logPath))
scanner := bufio.NewScanner(readFile)
for scanner.Scan() {
s := scanner.Text() + "\r\n"
logFile.WriteString(s)
originalStdout.WriteString(s)
}
}()
}
//export start
func start() {
initShared()
main()
}
//export startWithLog
func startWithLog(log *C.char) int {
initLog(C.GoString(log))
main()
closeFiles()
return exit.Code
}
//export startWithArgs
func startWithArgs(args *C.char) int {
initShared()
exit.Args = C.GoString(args)
main()
return exit.Code
}
//export startWithLogAndArgs
func startWithLogAndArgs(logPath, args *C.char) int {
initShared()
initLog(C.GoString(logPath))
exit.Args = C.GoString(args)
main()
closeFiles()
// Give time to write everything to log files
time.Sleep(1 * time.Second)
return exit.Code
}
func closeFiles() {
if readFile != nil {
readFile.Close()
}
if writeFile != nil {
writeFile.Close()
}
}