Skip to content

Commit

Permalink
Address CRs
Browse files Browse the repository at this point in the history
Signed-off-by: Roger Standridge <[email protected]>
  • Loading branch information
archie2x committed Sep 16, 2024
1 parent ee82c9a commit 81f0c36
Show file tree
Hide file tree
Showing 3 changed files with 257 additions and 219 deletions.
2 changes: 1 addition & 1 deletion src/cmd/makebb/makebb.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func main() {
env.CgoEnabled = false
}

err = env.InitCompiler()
err = env.CompilerInit()
if err != nil {
l.Fatal(err)

Check warning on line 49 in src/cmd/makebb/makebb.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/makebb/makebb.go#L49

Added line #L49 was not covered by tests
}
Expand Down
224 changes: 6 additions & 218 deletions src/pkg/golang/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,10 @@
package golang

import (
"encoding/json"
"flag"
"fmt"
"go/build"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
Expand All @@ -30,15 +27,6 @@ const (
ModVendor ModBehavior = "vendor"
)

type Compiler struct {
Path string
Identifier string // e.g. 'tinygo' or 'go'
Version string // compiler-tool version
VersionGo string // version of go: same as 'Version' for standard go
VersionOutput string // output of calling 'tool version'
IsInit bool // InitCompiler() succeeded
}

// Environ are the environment variables for the Go compiler.
type Environ struct {
build.Context
Expand Down Expand Up @@ -68,7 +56,7 @@ func (c *Environ) RegisterFlags(f *flag.FlagSet) {
f.Var((*uflag.Strings)(&c.BuildTags), "go-build-tags", "Go build tags")
f.StringVar((*string)(&c.Mod), "go-mod", string(c.Mod), "Value of -mod to go commands (allowed: (empty), vendor, mod, readonly)")
f.StringVar((*string)(&c.Compiler.Path), "compiler", "",
"override go compiler to use (e.g. \"/path/to/tinygo\")")
"override go compiler used (e.g. \"/path/to/tinygo\")")
}

// Valid returns an error if GOARCH, GOROOT, or GOOS are unset.
Expand Down Expand Up @@ -168,13 +156,6 @@ func WithWorkingDir(wd string) Opt {
}
}

// WithCompiler sets the compiler for Build() / BuildDir()
func WithCompiler(p string) Opt {
return func(c *Environ) {
c.Compiler.Path = p
}
}

// Default is the default build environment comprised of the default GOPATH,
// GOROOT, GOOS, GOARCH, and CGO_ENABLED values.
func Default(opts ...Opt) *Environ {
Expand All @@ -198,16 +179,19 @@ func (c *Environ) Apply(opts ...Opt) {

// Lookup looks up packages by patterns relative to dir, using the Go environment from c.
func (c *Environ) Lookup(mode packages.LoadMode, patterns ...string) ([]*packages.Package, error) {
if err := c.InitCompiler(); err != nil {

// required to compute compiler build tags
if err := c.CompilerInit(); err != nil {
return nil, err

Check warning on line 185 in src/pkg/golang/build.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/golang/build.go#L185

Added line #L185 was not covered by tests
}

cfg := &packages.Config{
Mode: mode,
Env: append(os.Environ(), c.Env()...),
Dir: c.Dir,
}
if len(c.Context.BuildTags) > 0 {
tags := fmt.Sprintf("-tags=%s", strings.Join(c.BuildTags, ","))
tags := fmt.Sprintf("-tags=%s", strings.Join(c.Context.BuildTags, ","))
cfg.BuildFlags = []string{tags}
}
if c.GO111MODULE != "off" && len(c.Mod) > 0 {
Expand All @@ -216,125 +200,6 @@ func (c *Environ) Lookup(mode packages.LoadMode, patterns ...string) ([]*package
return packages.Load(cfg, patterns...)
}

// GoCmd runs a go command in the environment.
func (c Environ) GoCmd(gocmd string, args ...string) *exec.Cmd {
goBin := c.Compiler.Path
if "" == goBin {
goBin = filepath.Join(c.GOROOT, "bin", "go")
}
args = append([]string{gocmd}, args...)
cmd := exec.Command(goBin, args...)
if c.GBBDEBUG {
log.Printf("GBB Go invocation: %s %s %#v", c, goBin, args)
}
cmd.Dir = c.Dir
cmd.Env = append(os.Environ(), c.Env()...)
return cmd
}

// resolve absolute path of go-compiler option from PATH
func (c *Environ) resolveCompiler() error {
if c.Compiler.Path != "" {
fname, err := exec.LookPath(string(c.Compiler.Path))
if err == nil {
fname, err = filepath.Abs(fname)
}
if err != nil {
return fmt.Errorf("build: %v", err)
}
c.Compiler.Path = fname
}
return nil
}

// runs GoCmd("version") and parse/caches output, to environ.Compiler
func (c *Environ) InitCompiler() error {

if c.Compiler.IsInit {
return nil
}

c.resolveCompiler()

cmd := c.GoCmd("version")
v, err := cmd.CombinedOutput()
if err != nil {
return err
}

efmt := "go-compiler 'version' output unrecognized: %v"
s := strings.Fields(string(v))
if len(s) < 1 {
return fmt.Errorf(efmt, string(v))
}

compiler := c.Compiler
compiler.Identifier = s[0]
compiler.VersionOutput = string(v)
compiler.IsInit = true

switch compiler.Identifier {

case "go":
if len(s) < 3 {
return fmt.Errorf(efmt, string(v))
}
compiler.Version = s[2]
compiler.VersionGo = s[2]

case "tinygo":
// e.g. "tinygo version 0.33.0 darwin/arm64 (using go version go1.22.2 and LLVM version 18.1.2)"
if len(s) < 8 {
return fmt.Errorf(efmt, string(v))
}
compiler.Version = s[2]
compiler.VersionGo = s[7]

// Fetch additional go-build-tags from tinygo
// package fetch needs correct tags to prune
cmd := c.GoCmd("info", "-json")
infov, err := cmd.CombinedOutput()
if err != nil {
return err
}
var info map[string]interface{}
err = json.Unmarshal(infov, &info)
if err != nil {
return err
}
tags := []string{}
unique := make(map[string]bool)
addUnique := func(tag string) {
if unique[tag] {
return
}
unique[tag] = true
tags = append(tags, tag)
}
for _, tag := range c.BuildTags {
addUnique(tag)
}
for _, tag := range info["build_tags"].([]interface{}) {
addUnique(tag.(string))
}
c.BuildTags = tags

default:
return fmt.Errorf(efmt, string(v))
}
c.Compiler = compiler
return nil
}

// Version returns the Go version string that runtime.Version would return for
// the Go compiler in this environ.
func (c *Environ) Version() (string, error) {
if err := c.InitCompiler(); err != nil {
return "", err
}
return c.Compiler.VersionGo, nil
}

func (c Environ) envCommon() []string {
var env []string
if c.GOARCH != "" {
Expand Down Expand Up @@ -416,83 +281,6 @@ func (b *BuildOpts) RegisterFlags(f *flag.FlagSet) {
f.Var((*uflag.Strings)(&b.ExtraArgs), "go-extra-args", "Extra args to 'go build'")
}

func (c Environ) build(dirPath string, binaryPath string, pattern []string, opts *BuildOpts) error {

if err := c.InitCompiler(); err != nil {
return err
}

args := []string{
"-o", binaryPath,
}

if c.GO111MODULE != "off" && len(c.Mod) > 0 {
args = append(args, "-mod", string(c.Mod))
}
if c.InstallSuffix != "" {
args = append(args, "-installsuffix", c.Context.InstallSuffix)
}

switch c.Compiler.Identifier {
case "go":

// Force rebuilding of packages.
args = append(args, "-a")

if opts == nil || !opts.EnableInlining {
// Disable "function inlining" to get a (likely) smaller binary.
args = append(args, "-gcflags=all=-l")
}

if opts == nil || !opts.NoStrip {
// Strip all symbols, and don't embed a Go build ID to be reproducible.
args = append(args, "-ldflags", "-s -w -buildid=")
}

if opts == nil || !opts.NoTrimPath {
// Reproducible builds: Trim any GOPATHs out of the executable's
// debugging information.
//
// E.g. Trim /tmp/bb-*/ from /tmp/bb-12345567/src/github.com/...
args = append(args, "-trimpath")
}

case "tinygo":

// TODO: handle force-rebuild of packages (-a to standard go)
// TODO: handle EnableInlining

// Strip all symbols. TODO: not sure about buildid
if opts == nil || !opts.NoStrip {
// Strip all symbols
args = append(args, "-no-debug")
}

// TODO: handle NoTrimpPath

}

if len(c.BuildTags) > 0 {
args = append(args, fmt.Sprintf("-tags=%s", strings.Join(c.BuildTags, ",")))
}

if opts != nil {
args = append(args, opts.ExtraArgs...)
}

args = append(args, pattern...)

cmd := c.GoCmd("build", args...)
if dirPath != "" {
cmd.Dir = dirPath
}

if o, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("error building go package in %q: %v, %v", dirPath, string(o), err)
}
return nil
}

// BuildDir compiles the package in the directory `dirPath`, writing the build
// object to `binaryPath`.
func (c Environ) BuildDir(dirPath string, binaryPath string, opts *BuildOpts) error {
Expand Down
Loading

0 comments on commit 81f0c36

Please sign in to comment.