Select Git revision
handlers.go
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
go_compiler.go 1.96 KiB
package go_compiler_v2
import (
"compiler_V2/consts"
"compiler_V2/utils"
"os"
"regexp"
)
const fileName = "main.go"
const testFileName = "main_test.go"
type GoCompiler struct{}
// NewGoCompiler creates a new GoCompiler
func NewGoCompiler() *GoCompiler {
return &GoCompiler{}
}
// CheckCompileErrors takes Go source code and checks for compile errors.
//
// The dependencies are handled automatically by go mod and go tidy.
//
// NOTE: Make sure you have an up-to-date Go installed on the system
//
// Returns the output of the compilation and an error if any
func (gb *GoCompiler) CheckCompileErrors(srcCode []byte) ([]byte, error) {
// Make temp folders
utils.SetupTempFolders(consts.TempOutputDir)
defer utils.RemoveTempFolders(consts.TempOutputDir)
// Create regex to extract test functions from srcCode
re := regexp.MustCompile(`(?m)^func\s+(Test\w+)\s*\(t\s+\*testing\.T\)\s*{[\s\S]*?^}`)
// Get all test functions from srcCode
testFunctions := re.FindAllString(string(srcCode), -1)
// Remove the test code from the main code
nonTestContent := re.ReplaceAllString(string(srcCode), "")
// Write code to main file
err := os.WriteFile(consts.TempOutputDir+fileName, []byte(nonTestContent), 0644)
if err != nil {
return nil, err
}
// Construct the content for the _test.go file.
testFileContent := "package main\n\n"
for _, match := range testFunctions {
testFileContent += match + "\n\n"
}
// Write code to test file, we need this since the tests are in the same file as the code
err2 := os.WriteFile(consts.TempOutputDir+testFileName, []byte(testFileContent), 0644)
if err2 != nil {
return nil, err2
}
// Init go mod, tidy (for dependencies) and goimports (for imports)
cmdString := "go mod init tempOutput && go mod tidy && goimports -w ."
// Run go build
cmdString += " && go build -o main " + fileName
// Run tests
cmdString += " && go test -v "
cmd := utils.MakeCommand(cmdString)
cmd.Dir = consts.TempOutputDir
return cmd.CombinedOutput()
}