From 0efacf0ca948a9bc62d09ba671392e3462343c93 Mon Sep 17 00:00:00 2001 From: lyyyuna Date: Fri, 10 Jul 2020 11:05:54 +0800 Subject: [PATCH] add unit test for #43 --- cmd/build_test.go | 28 ++++++++++++++++++++++++++++ pkg/build/build.go | 23 ++++++++++------------- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/cmd/build_test.go b/cmd/build_test.go index 9d46dee..b0d8e70 100644 --- a/cmd/build_test.go +++ b/cmd/build_test.go @@ -60,3 +60,31 @@ func TestGeneratedBinary(t *testing.T) { cnt = strings.Count(string(out), "GoCover") assert.Equal(t, cnt > 0, true, "GoCover varibale should be in the binary") } + +func TestBuildBinaryName(t *testing.T) { + startTime := time.Now() + + workingDir := filepath.Join(baseDir, "../tests/samples/simple_project2") + gopath := "" + + os.Setenv("GOPATH", gopath) + os.Setenv("GO111MODULE", "on") + + buildFlags, buildOutput = "", "" + args := []string{"."} + runBuild(args, workingDir) + + obj := filepath.Join(workingDir, "simple-project") + fInfo, err := os.Lstat(obj) + assert.Equal(t, err, nil, "the binary should be generated.") + assert.Equal(t, startTime.Before(fInfo.ModTime()), true, obj+"new binary should be generated, not the old one") + + cmd := exec.Command("go", "tool", "objdump", "simple-project") + cmd.Dir = workingDir + out, _ := cmd.CombinedOutput() + cnt := strings.Count(string(out), "main.registerSelf") + assert.Equal(t, cnt > 0, true, "main.registerSelf function should be in the binary") + + cnt = strings.Count(string(out), "GoCover") + assert.Equal(t, cnt > 0, true, "GoCover varibale should be in the binary") +} diff --git a/pkg/build/build.go b/pkg/build/build.go index 53b8ce4..b326253 100644 --- a/pkg/build/build.go +++ b/pkg/build/build.go @@ -115,21 +115,18 @@ func (b *Build) determineOutputDir(outputDir string) (string, error) { return "", fmt.Errorf("can only be called after Build.MvProjectsToTmp(): %w", ErrWrongCallSequence) } - if outputDir == "" { - _, last := filepath.Split(b.WorkingDir) - if b.IsMod { - // in mod, special rule - // replace "_" with "-" in the import path - last = strings.ReplaceAll(last, "_", "-") + // fix #43 + // use target name from `go list -json ./...` of the main module + targetName := "" + for _, pkg := range b.Pkgs { + if pkg.Name == "main" { + _, file := filepath.Split(pkg.Target) + targetName = file + break } - return filepath.Join(b.WorkingDir, last), nil } - abs, err := filepath.Abs(outputDir) - if err != nil { - log.Errorf("Fail to transform the path: %v to absolute path: %v", outputDir, err) - return "", err - } - return abs, nil + + return filepath.Join(b.WorkingDir, targetName), nil } // validatePackageForBuild only allow . as package name