forked from getgauge/gauge-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gauge-java.go
479 lines (424 loc) · 12.4 KB
/
gauge-java.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// Copyright 2015 ThoughtWorks, Inc.
// This file is part of Gauge-Java.
// This program is free software.
//
// It is dual-licensed under:
// 1) the GNU General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version;
// or
// 2) the Eclipse Public License v1.0.
//
// You can redistribute it and/or modify it under the terms of either license.
// We would then provide copied of each license in a separate .txt file with the name of the license as the title of the file.
package main
import (
"bufio"
"flag"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"github.com/getgauge/common"
"path"
)
const (
alternate_java_home = "gauge_java_home"
java_home = "JAVA_HOME"
additional_libs_env_name = "gauge_additional_libs"
custom_build_path = "gauge_custom_build_path"
custom_compile_dir = "gauge_custom_compile_dir"
custom_classpath = "gauge_custom_classpath"
jvm_args_env_name = "gauge_jvm_args"
default_build_dir = "gauge_bin"
main_class_name = "com.thoughtworks.gauge.GaugeRuntime"
step_implementation_class = "StepImplementation.java"
skelDir = "skel"
envDir = "env"
JavaDebugOptsTemplate = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=%s,timeout=25000"
java = "java"
javaExt = ".java"
defaultSrcDir = "src"
windows = "windows"
)
var pluginDir = ""
var projectRoot = ""
var start = flag.Bool("start", false, "Start the java runner")
var initialize = flag.Bool("init", false, "Initialize the java runner")
func main() {
flag.Parse()
setPluginAndProjectRoots()
if *start {
startJava()
} else if *initialize {
initializeProject()
} else {
printUsage()
}
}
func initializeProject() {
os.Chdir(projectRoot)
funcs := []initializerFunc{createSrcDirectory, createLibsDirectory, createStepImplementationClass, createEnvDir, createJavaPropertiesFile, createOrAppendGitignore}
for _, f := range funcs {
f()
}
}
func startJava() {
os.Chdir(projectRoot)
cp := customClasspath()
if cp == "" {
cp = createClasspath()
}
javaPath := getExecPathFrom(java_home, alternate_java_home, execName(java))
args := createCommandArgs()
cmd := runJavaCommandAsync(javaPath, args, cp)
listenForKillSignal(cmd)
go killIfGaugeIsDead(cmd) // Kills gauge-java.go process if gauge process i.e. parent process is already dead.
err := cmd.Wait()
if err != nil {
fmt.Printf("process %s with pid %d quit unexpectedly. %s\n", cmd.Path, cmd.Process.Pid, err.Error())
os.Exit(1)
}
}
func listenForKillSignal(cmd *exec.Cmd) {
sigc := make(chan os.Signal, 2)
signal.Notify(sigc, syscall.SIGTERM)
go func() {
<-sigc
cmd.Process.Kill()
}()
}
func killIfGaugeIsDead(cmd *exec.Cmd) {
parentProcessID := os.Getppid()
for {
if !isProcessRunning(parentProcessID) {
// fmt.Printf("Parent Gauge process with pid %d has terminated.", parentProcessID)
err := cmd.Process.Kill()
if err != nil {
fmt.Printf("Failed to kill process with pid %d. %s\n", cmd.Process.Pid, err.Error())
}
os.Exit(0)
}
time.Sleep(100 * time.Millisecond)
}
}
func isProcessRunning(pid int) bool {
process, err := os.FindProcess(pid)
if err != nil {
return false
}
if runtime.GOOS != windows {
return process.Signal(syscall.Signal(0)) == nil
}
processState, err := process.Wait()
if err != nil {
return false
}
if processState.Exited() {
return false
}
return true
}
func createCommandArgs() []string {
args := []string{}
javaDebugPort := os.Getenv(common.GaugeDebugOptsEnv)
if javaDebugPort != "" {
value := fmt.Sprintf(JavaDebugOptsTemplate, javaDebugPort)
args = append(args, value)
}
if os.Getenv(jvm_args_env_name) != "" {
jvmArgs := splitByComma(os.Getenv(jvm_args_env_name))
args = append(args, jvmArgs...)
}
args = append(args, encoding())
args = append(args, main_class_name)
return args
}
func encoding() string {
return "-Dfile.encoding=UTF-8"
}
func execName(name string) string {
if runtime.GOOS == windows {
return fmt.Sprintf("%s.exe", name)
}
return name
}
func setPluginAndProjectRoots() {
var err error
pluginDir, err = os.Getwd()
if err != nil {
fmt.Printf("Failed to find current working directory: %s \n", err)
os.Exit(1)
}
projectRoot = os.Getenv(common.GaugeProjectRootEnv)
if projectRoot == "" {
fmt.Printf("Could not find %s env. Java Runner exiting...", common.GaugeProjectRootEnv)
os.Exit(1)
}
}
func appendClasspath(source *string, classpath string) {
if len(classpath) == 0 {
return
}
if len(*source) == 0 {
*source = classpath
} else {
*source = fmt.Sprintf("%s%c%s", *source, os.PathListSeparator, classpath)
}
}
// User set classpath & additional libs will be comma separated
// it could be relative path, but JVM needs full path to be specified
// so this function splits the path, convert them to absolute path forms a classpath
func getClassPathForVariable(envVariableName string) string {
value := os.Getenv(envVariableName)
cp := ""
if len(value) > 0 {
paths := splitByComma(value)
for _, p := range paths {
abs, err := filepath.Abs(p)
if err == nil {
appendClasspath(&cp, abs)
} else {
appendClasspath(&cp, p)
}
}
}
return cp
}
type initializerFunc func()
func showMessage(action, filename string) {
fmt.Printf(" %s %s\n", action, filename)
}
func createSrcDirectory() {
createDirectory(filepath.Join(defaultSrcDir, "test", java))
}
func createLibsDirectory() {
createDirectory("libs")
}
func createEnvDir() {
createDirectory(path.Join(projectRoot, "env", "default"))
}
func createDirectory(filePath string) {
showMessage("create", filePath)
if !common.DirExists(filePath) {
err := os.MkdirAll(filePath, 0755)
if err != nil {
fmt.Printf("Failed to make directory. %s\n", err.Error())
}
} else {
showMessage("skip", filePath)
}
}
func createStepImplementationClass() {
javaSrc := filepath.Join(defaultSrcDir, "test", java)
destFile := filepath.Join(javaSrc, step_implementation_class)
showMessage("create", destFile)
if common.FileExists(destFile) {
showMessage("skip", destFile)
} else {
srcFile := filepath.Join(pluginDir, skelDir, step_implementation_class)
if !common.FileExists(srcFile) {
showMessage("error", fmt.Sprintf("%s Does not exist.\n", step_implementation_class))
return
}
err := common.CopyFile(srcFile, destFile)
if err != nil {
showMessage("error", fmt.Sprintf("Failed to copy %s. %s \n", srcFile, err.Error()))
}
}
}
func createJavaPropertiesFile() {
destFile := filepath.Join(envDir, "default", "java.properties")
showMessage("create", destFile)
if common.FileExists(destFile) {
showMessage("skip", destFile)
} else {
srcFile := filepath.Join(pluginDir, skelDir, envDir, "java.properties")
if !common.FileExists(srcFile) {
showMessage("error", fmt.Sprintf("java.properties does not exist at %s. \n", srcFile))
return
}
err := common.CopyFile(srcFile, destFile)
if err != nil {
showMessage("error", fmt.Sprintf("Failed to copy %s. %s \n", srcFile, err.Error()))
}
}
}
func createOrAppendGitignore() {
destFile := filepath.Join(projectRoot, ".gitignore")
srcFile := filepath.Join(pluginDir, skelDir, ".gitignore")
showMessage("create", destFile)
if err := common.AppendToFile(srcFile, destFile); err != nil {
showMessage("error", err.Error())
}
}
func printUsage() {
flag.PrintDefaults()
os.Exit(2)
}
func runJavaCommand(cmdName string, args []string, classpath string, printErrorsOnFailure bool) {
cmd := runJavaCommandAsync(cmdName, args, classpath)
err := cmd.Wait()
if err != nil {
if printErrorsOnFailure {
fmt.Printf("process %s with pid %d quit unexpectedly. %s\n", cmd.Path, cmd.Process.Pid, err.Error())
}
os.Exit(1)
}
}
func runJavaCommandAsync(cmdName string, args []string, classpath string) *exec.Cmd {
cmd := exec.Command(cmdName, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
os.Setenv("CLASSPATH", classpath)
//TODO: move to logs
/*fmt.Println(cmd.Args)*/
var err error
err = cmd.Start()
if err != nil {
fmt.Printf("Failed to start %s. %s\n", cmd.Path, err.Error())
os.Exit(1)
}
return cmd
}
func customClasspath() string {
return os.Getenv(custom_classpath)
}
func createClasspath() string {
cp := ""
appendClasspath(&cp, filepath.Join(pluginDir, "*"))
appendClasspath(&cp, filepath.Join(pluginDir, "libs", "*"))
additionalLibs := getClassPathForVariable(additional_libs_env_name)
appendClasspath(&cp, additionalLibs)
// If user has specified classpath, that will be taken. If not search for IntelliJ and Eclipse out directories before giving up
userSpecifiedClasspath := getClassPathForVariable(custom_build_path)
if userSpecifiedClasspath != "" {
appendClasspath(&cp, userSpecifiedClasspath)
} else {
//TODO: Move to log
//fmt.Println("Failed to detect project build path")
//fmt.Printf("Building to %s directory \n", default_build_dir)
build(default_build_dir, cp)
appendClasspath(&cp, default_build_dir)
}
return cp
}
func getExecPathFrom(path string, alternatePath string, execName string) string {
var execPath string
home := os.Getenv(alternatePath)
if home == "" {
home = os.Getenv(path)
if home == "" {
return execName
}
}
filepath.Walk(home, func(currentPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.Name() == execName {
execPath = currentPath
}
return err
})
if execPath != "" {
return execPath
}
return execName
}
func build(destination string, classpath string) {
os.RemoveAll(destination)
os.Mkdir(destination, 0755)
args := []string{"-encoding", "UTF-8", "-d", destination}
javaFiles := make([]string, 0)
resourceFiles := make(map[string][]string, 0)
srcDirs := make([]string, 0)
value := os.Getenv(custom_compile_dir)
if len(value) > 0 {
paths := splitByComma(value)
for _, src := range paths {
srcDirs = append(srcDirs, src)
}
}
srcDirs = append(srcDirs, defaultSrcDir)
for _, srcDirItem := range srcDirs {
filepath.Walk(srcDirItem, func(currentPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if filepath.Ext(currentPath) == javaExt {
javaFiles = append(javaFiles, currentPath)
} else if !info.IsDir() {
if _, ok := resourceFiles[srcDirItem]; !ok {
resourceFiles[srcDirItem] = make([]string, 0)
}
listOfFiles := resourceFiles[srcDirItem]
listOfFiles = append(listOfFiles, currentPath)
resourceFiles[srcDirItem] = listOfFiles
}
return nil
})
}
if len(javaFiles) == 0 {
return
}
// Writing all java src file names to a file and using it as a @filename parameter to javac. Eg: javac -cp jar1:jar2 @sources.txt
// This needs to be done because if the number of java files is too high the command length will be more than that permitted by the os.
tempDir := common.GetTempDir()
defer os.RemoveAll(tempDir)
sourcesFile := filepath.Join(tempDir, uniqueFileName())
if err := writeLines(javaFiles, sourcesFile); err != nil {
panic("Unable to write file: " + err.Error())
}
args = append(args, "@"+sourcesFile)
javac := getExecPathFrom(java_home, alternate_java_home, execName("javac"))
//TODO: should move to logs
//fmt.Println(fmt.Sprintf("Building files in %s directory to %s", "src", destination))
runJavaCommand(javac, args, classpath, false)
copyResources(resourceFiles, destination)
}
func uniqueFileName() string {
return fmt.Sprintf("%d", common.GetUniqueID())
}
func writeLines(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
}
return w.Flush()
}
func copyResources(srcFilesMap map[string][]string, dest string) {
for src, files := range srcFilesMap {
for _, file := range files {
if src == defaultSrcDir {
copyResource(filepath.Join(defaultSrcDir, "test", "java"), file, default_build_dir)
} else {
copyResource(src, file, default_build_dir)
}
}
}
}
func copyResource(basePath string, resource string, destination string) error {
rel, err := filepath.Rel(basePath, resource)
if err != nil {
return err
}
return common.MirrorFile(resource, filepath.Join(destination, rel))
}
func splitByComma(text string) []string {
splits := make([]string, 0)
values := strings.Split(text, ",")
for _, val := range values {
splits = append(splits, strings.TrimSpace(val))
}
return splits
}