diff --git a/modules/compiler_v2/go_compiler_v2/go_compiler.go b/modules/compiler_v2/go_compiler_v2/go_compiler.go index 800797b92fd3d5cd83723cfe5db05a120d91d590..ead228f6281c5930a82ed521aa656baf5e086850 100644 --- a/modules/compiler_v2/go_compiler_v2/go_compiler.go +++ b/modules/compiler_v2/go_compiler_v2/go_compiler.go @@ -4,9 +4,11 @@ import ( "compiler_V2/consts" "compiler_V2/utils" "os" + "regexp" ) const fileName = "main.go" +const testFileName = "main_test.go" type GoCompiler struct{} @@ -27,19 +29,41 @@ func (gb *GoCompiler) CheckCompileErrors(srcCode []byte) ([]byte, error) { utils.SetupTempFolders(consts.TempOutputDir) defer utils.RemoveTempFolders(consts.TempOutputDir) - // Write code to file - err := os.WriteFile(consts.TempOutputDir+fileName, srcCode, 0644) + // 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 } - // Init go mod and tidy - cmdString := "go mod init tempOutput && go mod tidy " + + // 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 " + fileName + cmdString += " && go test -v " cmd := utils.MakeCommand(cmdString) cmd.Dir = consts.TempOutputDir