github.com/adacta-ru/mattermost-server/v6@v6.0.0/utils/test_files_compiler.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package utils 5 6 import ( 7 "bytes" 8 "io/ioutil" 9 "os" 10 "os/exec" 11 "path/filepath" 12 "runtime" 13 "testing" 14 15 "github.com/stretchr/testify/require" 16 ) 17 18 func CompileGo(t *testing.T, sourceCode, outputPath string) { 19 dir, err := ioutil.TempDir(".", "") 20 require.NoError(t, err) 21 defer os.RemoveAll(dir) 22 23 dir, err = filepath.Abs(dir) 24 require.NoError(t, err) 25 26 // Write out main.go given the source code. 27 main := filepath.Join(dir, "main.go") 28 err = ioutil.WriteFile(main, []byte(sourceCode), 0600) 29 require.NoError(t, err) 30 31 _, sourceFile, _, ok := runtime.Caller(0) 32 require.True(t, ok) 33 serverPath := filepath.Dir(filepath.Dir(sourceFile)) 34 35 out := &bytes.Buffer{} 36 cmd := exec.Command("go", "build", "-o", outputPath, main) 37 cmd.Dir = serverPath 38 cmd.Stdout = out 39 cmd.Stderr = out 40 err = cmd.Run() 41 if err != nil { 42 t.Log("Go compile errors:\n", out.String()) 43 } 44 require.NoError(t, err, "failed to compile go") 45 }