Skip to content

Commit 0a1e8c0

Browse files
committed
compute basename manually when target is missing
fix #71
1 parent 27457c6 commit 0a1e8c0

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

packer/gotool.go

+27-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"log"
99
"os"
1010
"os/exec"
11+
"path"
1112
"path/filepath"
1213
"sort"
1314
"strings"
@@ -351,7 +352,32 @@ type Pkg struct {
351352
}
352353

353354
func (p *Pkg) Basename() string {
354-
return filepath.Base(p.Target)
355+
if p.Target != "" {
356+
return filepath.Base(p.Target)
357+
}
358+
// when GOBIN is set in the GOENV file, the target field is empty
359+
// see https://github.com/gokrazy/tools/issues/71
360+
base := path.Base(p.ImportPath)
361+
if isVersionElement(base) {
362+
return path.Base(path.Dir(p.ImportPath))
363+
}
364+
return base
365+
}
366+
367+
// isVersionElement reports whether s is a well-formed path version element:
368+
// v2, v3, v10, etc, but not v0, v05, v1.
369+
// copied from https://github.com/golang/go/blob/go1.22.5/src/cmd/go/internal/load/pkg.go#L1338
370+
// governed by a BSD-style license
371+
func isVersionElement(s string) bool {
372+
if len(s) < 2 || s[0] != 'v' || s[1] == '0' || s[1] == '1' && len(s) == 2 {
373+
return false
374+
}
375+
for i := 1; i < len(s); i++ {
376+
if s[i] < '0' || '9' < s[i] {
377+
return false
378+
}
379+
}
380+
return true
355381
}
356382

357383
func (be *BuildEnv) mainPackage(pkg string) ([]Pkg, error) {

packer/gotool_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package packer
2+
3+
import "testing"
4+
5+
func TestPkgBasename(t *testing.T) {
6+
f := func(p Pkg, wantBasename string) {
7+
t.Helper()
8+
got := p.Basename()
9+
if got != wantBasename {
10+
t.Errorf("pkg.Basename got %q, want %q", got, wantBasename)
11+
}
12+
}
13+
14+
f(Pkg{
15+
Target: "target-name",
16+
}, "target-name")
17+
18+
f(Pkg{
19+
ImportPath: "example.com/import/path",
20+
Target: "target-name",
21+
}, "target-name")
22+
23+
f(Pkg{
24+
ImportPath: "example.com/import/path",
25+
Target: "",
26+
}, "path")
27+
f(Pkg{
28+
ImportPath: "example.com/import/path/v2",
29+
Target: "",
30+
}, "path")
31+
}

0 commit comments

Comments
 (0)