vlp/internal/build/builder.go
2024-09-19 02:12:57 +02:00

72 lines
1.3 KiB
Go

package build
import (
"fmt"
"os"
"os/exec"
"code.vulpine.solutions/sam/vlp/internal/packages"
)
type Builder struct {
Name string
Version string
Dependencies []packages.Dependency
SourceFetcher Fetcher
Commands []BuildCommand
Binaries []string
TempDir string
}
type BuildCommand struct {
Command string
Args []string
}
func New(name, version string) (*Builder, error) {
b := &Builder{
Name: name,
Version: version,
}
tmp, err := tmpDir(name, version)
if err != nil {
return nil, err
}
b.TempDir = tmp
return b, nil
}
func (b *Builder) Build() error {
for i, cmd := range b.Commands {
exitCode, out := execCommand(cmd.Command, cmd.Args...)
if exitCode != 0 {
return fmt.Errorf("command %d returned exit code %d: %v", i, exitCode, string(out))
}
}
return nil
}
func tmpDir(name, version string) (string, error) {
tmp, err := os.MkdirTemp(os.TempDir(), "vlp-build-"+name+"-"+version+"_")
if err != nil {
return "", fmt.Errorf("creating temp dir: %w", err)
}
return tmp, nil
}
func execCommand(bin string, args ...string) (int, []byte) {
err := exec.Command(bin, args...).Run()
if err != nil {
eErr, ok := err.(*exec.ExitError)
if ok {
return eErr.ExitCode(), eErr.Stderr
}
return 1, nil
}
return 0, nil
}