|
| 1 | +package loader |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "os/exec" |
| 7 | + "path/filepath" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/cmepw/221b/logger" |
| 11 | + "github.com/cmepw/221b/templates" |
| 12 | +) |
| 13 | + |
| 14 | +type Loader interface { |
| 15 | + Load(content []byte) ([]byte, error) |
| 16 | + Compile(path string, content []byte) error |
| 17 | +} |
| 18 | + |
| 19 | +type baseLoader struct{} |
| 20 | + |
| 21 | +const ( |
| 22 | + windowsExt = ".exe" |
| 23 | + tmpFile = "tmp.go" |
| 24 | +) |
| 25 | + |
| 26 | +func (b baseLoader) Compile(path string, content []byte) error { |
| 27 | + outputPath := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) + windowsExt |
| 28 | + |
| 29 | + dir := "/tmp/test" |
| 30 | + if err := os.MkdirAll(dir, 0750); err != nil { |
| 31 | + logger.Error(fmt.Errorf("could not create temporary directory")) |
| 32 | + return err |
| 33 | + } |
| 34 | + |
| 35 | + defer func() { |
| 36 | + _ = os.RemoveAll(dir) |
| 37 | + }() |
| 38 | + |
| 39 | + // Set environment |
| 40 | + logger.Debug("write content to temporary file") |
| 41 | + if err := os.WriteFile(filepath.Join(dir, tmpFile), content, 0666); err != nil { |
| 42 | + logger.Error(fmt.Errorf("could not write tmp file")) |
| 43 | + return err |
| 44 | + } |
| 45 | + |
| 46 | + if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(templates.GoMod), 0666); err != nil { |
| 47 | + logger.Error(fmt.Errorf("could not write tmp go.mod file")) |
| 48 | + return err |
| 49 | + } |
| 50 | + |
| 51 | + initCmd := exec.Command("go", "get", "-u", "golang.org/x/sys/windows") |
| 52 | + initCmd.Dir = dir |
| 53 | + initCmd.Stderr = os.Stderr |
| 54 | + initCmd.Env = append(os.Environ(), "GOOS=windows", "GOARCH=amd64") |
| 55 | + if err := initCmd.Run(); err != nil { |
| 56 | + logger.Error(fmt.Errorf("could not install dependency")) |
| 57 | + return err |
| 58 | + } |
| 59 | + |
| 60 | + logger.Debug("dependency installed") |
| 61 | + |
| 62 | + pwd, err := os.Getwd() |
| 63 | + if err != nil { |
| 64 | + return err |
| 65 | + } |
| 66 | + |
| 67 | + buildCmd := exec.Command( |
| 68 | + "go", |
| 69 | + "build", |
| 70 | + "-ldflags", |
| 71 | + "-s -w -H=windowsgui", |
| 72 | + "-o", |
| 73 | + filepath.Join(pwd, outputPath), |
| 74 | + filepath.Join(dir, tmpFile), |
| 75 | + ) |
| 76 | + buildCmd.Env = append(os.Environ(), "GOOS=windows", "GOARCH=amd64") |
| 77 | + buildCmd.Stderr = os.Stderr |
| 78 | + buildCmd.Dir = dir |
| 79 | + |
| 80 | + if err := buildCmd.Run(); err != nil { |
| 81 | + logger.Error(fmt.Errorf("failed to compile")) |
| 82 | + return err |
| 83 | + } |
| 84 | + |
| 85 | + logger.Info(fmt.Sprintf("file compiled to %s", filepath.Join(pwd, outputPath))) |
| 86 | + return nil |
| 87 | +} |
0 commit comments