Skip to content
Snippets Groups Projects
Commit 8af937f4 authored by Aleksander Einarsen's avatar Aleksander Einarsen
Browse files

#86 Compiler splits main code and test code into two files using regex. Added...

#86 Compiler splits main code and test code into two files using regex. Added go test for testing and goimport for handling import syntax errors.
parent 1f17a207
Branches
No related tags found
No related merge requests found
...@@ -4,9 +4,11 @@ import ( ...@@ -4,9 +4,11 @@ import (
"compiler_V2/consts" "compiler_V2/consts"
"compiler_V2/utils" "compiler_V2/utils"
"os" "os"
"regexp"
) )
const fileName = "main.go" const fileName = "main.go"
const testFileName = "main_test.go"
type GoCompiler struct{} type GoCompiler struct{}
...@@ -27,19 +29,41 @@ func (gb *GoCompiler) CheckCompileErrors(srcCode []byte) ([]byte, error) { ...@@ -27,19 +29,41 @@ func (gb *GoCompiler) CheckCompileErrors(srcCode []byte) ([]byte, error) {
utils.SetupTempFolders(consts.TempOutputDir) utils.SetupTempFolders(consts.TempOutputDir)
defer utils.RemoveTempFolders(consts.TempOutputDir) defer utils.RemoveTempFolders(consts.TempOutputDir)
// Write code to file // Create regex to extract test functions from srcCode
err := os.WriteFile(consts.TempOutputDir+fileName, srcCode, 0644) 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 { if err != nil {
return nil, err 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 // Run go build
cmdString += " && go build -o main " + fileName cmdString += " && go build -o main " + fileName
// Run tests // Run tests
cmdString += " && go test " + fileName cmdString += " && go test -v "
cmd := utils.MakeCommand(cmdString) cmd := utils.MakeCommand(cmdString)
cmd.Dir = consts.TempOutputDir cmd.Dir = consts.TempOutputDir
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment