github.com/wawandco/oxpecker-plugins@v0.1.1/tools/standard/build.go (about)

     1  package standard
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"os/exec"
     7  
     8  	"github.com/wawandco/oxpecker-plugins/internal/info"
     9  )
    10  
    11  // Build runs the Go compiler to generate the desired binary. Assuming the
    12  // Go executable installed and can be invoked with `go`.
    13  //
    14  // IMPORTANT: it uses the static build flags.
    15  func (g *Plugin) Build(ctx context.Context, root string, args []string) error {
    16  	buildArgs, err := g.composeBuildArgs()
    17  	if err != nil {
    18  		return err
    19  	}
    20  
    21  	cmd := exec.CommandContext(ctx, "go", buildArgs...)
    22  	cmd.Stderr = os.Stderr
    23  	cmd.Stdout = os.Stdout
    24  	cmd.Stdin = os.Stdin
    25  
    26  	return cmd.Run()
    27  }
    28  
    29  func (g *Plugin) composeBuildArgs() ([]string, error) {
    30  	name, err := info.BuildName()
    31  	if err != nil {
    32  		return []string{}, err
    33  	}
    34  
    35  	buildArgs := []string{
    36  		"build",
    37  	}
    38  
    39  	//static
    40  	static := []string{
    41  		"--ldflags",
    42  		"-linkmode external",
    43  		"--ldflags",
    44  		`-extldflags "-static"`,
    45  	}
    46  
    47  	if g.static {
    48  		buildArgs = append(buildArgs, static...)
    49  	}
    50  	//o
    51  	o := []string{
    52  		"-o",
    53  		g.binaryOutput(name),
    54  	}
    55  	buildArgs = append(buildArgs, o...)
    56  
    57  	// add the build
    58  
    59  	if len(g.buildTags) != 0 {
    60  		buildArgs = append(buildArgs, "-tags")
    61  		buildArgs = append(buildArgs, g.buildTags...)
    62  	}
    63  
    64  	buildArgs = append(buildArgs, "./cmd/"+name)
    65  
    66  	return buildArgs, nil
    67  }
    68  
    69  // binaryOutput considers the output passed to
    70  // use it or default to bin/name.
    71  func (g *Plugin) binaryOutput(name string) string {
    72  	output := "bin/" + name
    73  	if g.output != "" {
    74  		output = g.output
    75  	}
    76  
    77  	return output
    78  }