-
Notifications
You must be signed in to change notification settings - Fork 2
/
loader.go
101 lines (77 loc) · 1.66 KB
/
loader.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
// Package ts contains xk6-ts extension.
package ts
import (
"os"
"path/filepath"
"time"
"github.com/grafana/k6pack"
"github.com/sirupsen/logrus"
)
func init() {
redirectStdin()
}
func isRunCommand(args []string) (bool, int) {
argn := len(args)
scriptIndex := argn - 1
if scriptIndex < 0 {
return false, scriptIndex
}
var runIndex int
for idx := 0; idx < argn; idx++ {
arg := args[idx]
if arg == "run" && runIndex == 0 {
runIndex = idx
break
}
}
if runIndex == 0 {
return false, -1
}
return true, scriptIndex
}
//nolint:forbidigo
func redirectStdin() {
if os.Getenv("XK6_TS") == "false" {
return
}
isRun, scriptIndex := isRunCommand(os.Args)
if !isRun {
return
}
filename := os.Args[scriptIndex]
if filename == "-" {
return
}
cwd, _ := os.Getwd()
opts := &k6pack.Options{
Filename: filename,
SourceMap: os.Getenv("XK6_TS_SOURCEMAP") != "false",
SourceRoot: cwd,
}
source, err := os.ReadFile(filepath.Clean(filename))
if err != nil {
logrus.WithError(err).Fatal()
}
packStarted := time.Now()
jsScript, err := k6pack.Pack(string(source), opts)
if err != nil {
logrus.WithError(err).Fatal()
}
if os.Getenv("XK6_TS_BENCHMARK") == "true" {
duration := time.Since(packStarted)
logrus.WithField("extension", "xk6-ts").WithField("duration", duration).Info("Bundling completed in ", duration)
}
os.Args[scriptIndex] = "-"
reader, writer, err := os.Pipe()
if err != nil {
logrus.WithError(err).Fatal()
}
os.Stdin = reader
go func() {
_, werr := writer.Write(jsScript)
writer.Close() //nolint:errcheck,gosec
if werr != nil {
logrus.WithError(werr).Fatal("stdin redirect failed")
}
}()
}