gocc/compile.go

84 lines
2.0 KiB
Go
Raw Normal View History

2022-08-17 18:47:09 +02:00
package main
import (
"os/exec"
2022-08-17 19:18:57 +02:00
"path/filepath"
"strings"
2022-08-17 18:47:09 +02:00
"sync"
2022-08-17 23:38:41 +02:00
"time"
2022-08-17 18:47:09 +02:00
)
func Compile(cfg *CompileConfig, ch chan<- *CompileReport, wg *sync.WaitGroup) {
2022-08-17 23:38:41 +02:00
start := time.Now()
// calculate filepath
b := new(strings.Builder)
data := &OutputFileTmplData{
Name: ProjectName,
OS: cfg.OS,
Arch: cfg.Arch,
Ext: cfg.FileExt,
}
if err := OutputFileTmpl.Execute(b, data); err != nil {
ch <- &CompileReport{Config: cfg, State: StateCompileError}
wg.Done()
return
}
filePath := filepath.Join(*OutputDir, b.String())
2022-08-17 19:18:57 +02:00
filePath, err := filepath.Abs(filePath)
if err != nil {
ch <- &CompileReport{Config: cfg, State: StateCompileError}
wg.Done()
return
}
2022-08-17 18:47:09 +02:00
ch <- &CompileReport{Config: cfg, State: StateCompiling}
2022-08-17 19:18:57 +02:00
compileCmd := exec.Command("go", "build", "-o", filePath)
2022-08-17 18:47:09 +02:00
compileCmd.Dir = ModulePath
if err := compileCmd.Start(); err != nil {
ch <- &CompileReport{Config: cfg, State: StateCompileError}
wg.Done()
return
}
if err := compileCmd.Wait(); err != nil {
ch <- &CompileReport{Config: cfg, State: StateCompileError}
wg.Done()
return
}
2022-08-17 23:38:41 +02:00
Compress(filePath, start, cfg, ch, wg)
2022-08-17 18:47:09 +02:00
// uncomment for independent compile and compress tasks
// (slightly slower in tests, most likely because of more context switches)
/*
ch <- &CompileReport{Config: cfg, State: StateWaiting}
2022-08-17 19:18:57 +02:00
go Runner.Run(func() { Compress(filePath, cfg, ch, wg) })
2022-08-17 18:47:09 +02:00
*/
}
2022-08-17 23:38:41 +02:00
func Compress(filePath string, start time.Time, cfg *CompileConfig, ch chan<- *CompileReport, wg *sync.WaitGroup) {
2022-08-17 18:47:09 +02:00
defer wg.Done()
ch <- &CompileReport{Config: cfg, State: StateCompressing}
if !*NoCompress && cfg.Compress {
2022-08-17 19:18:57 +02:00
compressCmd := exec.Command("upx", "--best", filePath)
2022-08-17 18:47:09 +02:00
compressCmd.Dir = ModulePath
if err := compressCmd.Start(); err != nil {
ch <- &CompileReport{Config: cfg, State: StateCompressError}
return
}
if err := compressCmd.Wait(); err != nil {
ch <- &CompileReport{Config: cfg, State: StateCompressError}
return
}
}
2022-08-17 23:38:41 +02:00
ch <- &CompileReport{Config: cfg, State: StateDone, Duration: time.Since(start)}
2022-08-17 18:47:09 +02:00
}