Skip to content

Commit

Permalink
refactor: update build.go to use custom executable for building new exes
Browse files Browse the repository at this point in the history
  • Loading branch information
ryan-gang committed Jul 30, 2024
1 parent cd5054c commit 837a2c9
Showing 1 changed file with 11 additions and 31 deletions.
42 changes: 11 additions & 31 deletions internal/custom_executable/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,52 +3,32 @@ package custom_executable
import (
_ "embed"
"fmt"
"os"
"os/exec"
"path"
"strings"
)

//go:embed main.txt
var content string

func ReplaceAndBuild(content, outputPath, placeholder, randomString string) error {
// regex replace placeholder with random string
content = strings.ReplaceAll(content, placeholder, randomString)

// write content to file
file, err := os.Create("tmp.go")
if err != nil {
return fmt.Errorf("CodeCrafters Internal Error: failed to create tmp.go: %w", err)
func ReplaceAndBuild(outputPath, randomString string) error {
// Our executable contains a placeholder for the random string
// The placeholder is <<<RANDOM>>>
// We will replace the placeholder with the random string
// The random string HAS to be the same length as the placeholder
if len(randomString) != 10 {
return fmt.Errorf("CodeCrafters Internal Error: randomString length must be 10")
}
defer file.Close()
file.WriteString(content)

// Run go build command
// ToDo: Remove log
goCmdFullPath := path.Join(os.Getenv("TESTER_DIR"), "go")
if goCmdFullPath == "go" {
return fmt.Errorf("CodeCrafters Internal Error: Couldn't find packaged go command.\nTESTER_DIR: %s", os.Getenv("TESTER_DIR"))
}
buildCmd := exec.Command(goCmdFullPath, "build", "-o", outputPath, "tmp.go")
command := fmt.Sprintf("echo -n \"%s\" | dd of=%s bs=1 seek=$((0x2070 + 4)) conv=notrunc", randomString, outputPath)
buildCmd := exec.Command("bash", "-c", command)
// buildCmd.Stdout = io.Discard
// buildCmd.Stderr = io.Discard
if err := buildCmd.Run(); err != nil {
return fmt.Errorf("CodeCrafters Internal Error: go build failed: %w", err)
}

err = os.Remove("tmp.go")
if err != nil {
return fmt.Errorf("CodeCrafters Internal Error: failed to remove tmp.go: %w", err)
return fmt.Errorf("CodeCrafters Internal Error: dd replace failed: %w", err)
}

return nil
}

func CreateExecutable(randomString, outputPath string) error {
// Define the file path, output path, and placeholder
placeholder := "PLACEHOLDER_RANDOM_STRING"

// Call the replaceAndBuild function
return ReplaceAndBuild(content, outputPath, placeholder, randomString)
return ReplaceAndBuild(outputPath, randomString)
}

0 comments on commit 837a2c9

Please sign in to comment.