cmd/go/internal/vcs: support git worktrees
Fixes golang/go#58218
diff --git a/src/cmd/go/internal/vcs/vcs.go b/src/cmd/go/internal/vcs/vcs.go
index 7c198c5..fdcefac 100644
--- a/src/cmd/go/internal/vcs/vcs.go
+++ b/src/cmd/go/internal/vcs/vcs.go
@@ -161,7 +161,7 @@
// config options or certain extensions.
Env: []string{"HGPLAIN=1"},
RootNames: []rootName{
- {filename: ".hg", isDir: true},
+ {filename: ".hg", isRoot: isDir},
},
CreateCmd: []string{"clone -U -- {repo} {dir}"},
@@ -250,7 +250,7 @@
Name: "Git",
Cmd: "git",
RootNames: []rootName{
- {filename: ".git", isDir: true},
+ {filename: ".git", isRoot: isDirOrWorktree},
},
CreateCmd: []string{"clone -- {repo} {dir}", "-go-internal-cd {dir} submodule update --init --recursive"},
@@ -364,7 +364,7 @@
Name: "Bazaar",
Cmd: "bzr",
RootNames: []rootName{
- {filename: ".bzr", isDir: true},
+ {filename: ".bzr", isRoot: isDir},
},
CreateCmd: []string{"branch -- {repo} {dir}"},
@@ -487,7 +487,7 @@
Name: "Subversion",
Cmd: "svn",
RootNames: []rootName{
- {filename: ".svn", isDir: true},
+ {filename: ".svn", isRoot: isDir},
},
CreateCmd: []string{"checkout -- {repo} {dir}"},
@@ -570,8 +570,8 @@
Name: "Fossil",
Cmd: "fossil",
RootNames: []rootName{
- {filename: ".fslckout", isDir: false},
- {filename: "_FOSSIL_", isDir: false},
+ {filename: ".fslckout", isRoot: isFile},
+ {filename: "_FOSSIL_", isRoot: isFile},
},
CreateCmd: []string{"-go-internal-mkdir {dir} clone -- {repo} " + filepath.Join("{dir}", fossilRepoName), "-go-internal-cd {dir} open .fossil"},
@@ -755,7 +755,7 @@
if !cfg.ModulesEnabled {
dir = filepath.Join(cfg.BuildContext.GOPATH, "src")
}
- os.MkdirAll(dir, 0777) // Ignore errors — if unsuccessful, the command will likely fail.
+ os.MkdirAll(dir, 0o777) // Ignore errors — if unsuccessful, the command will likely fail.
release, err := base.AcquireNet()
if err != nil {
@@ -932,18 +932,63 @@
// any of the listed root names.
func isVCSRoot(dir string, rootNames []rootName) bool {
for _, root := range rootNames {
- fi, err := os.Stat(filepath.Join(dir, root.filename))
- if err == nil && fi.IsDir() == root.isDir {
+ path := filepath.Join(dir, root.filename)
+ if root.isRoot(path) {
return true
}
}
-
return false
}
+// rootName specifies how to identify the root directory of a VCS.
type rootName struct {
- filename string
- isDir bool
+ filename string // name of file or directory to look for
+ isRoot func(path string) bool // isRoot reports whether path signifies a VCS root
+}
+
+// isDir reports whether path is a directory.
+func isDir(path string) bool {
+ fi, err := os.Stat(path)
+ return err == nil && fi.IsDir()
+}
+
+// isFile reports whether path is a regular file.
+func isFile(path string) bool {
+ fi, err := os.Stat(path)
+ return err == nil && fi.Mode().IsRegular()
+}
+
+// isDirOrWorktree reports whether path is a directory or a git worktree .git file.
+// See https://go.dev/issue/58218.
+func isDirOrWorktree(path string) bool {
+ fi, err := os.Stat(path)
+ if err != nil {
+ return false
+ }
+ if fi.IsDir() {
+ return true
+ }
+ // Is it a git worktree file?
+ // The format is "gitdir: <path>\n".
+ if !fi.Mode().IsRegular() || fi.Size() == 0 || fi.Size() > 4096 {
+ return false
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return false
+ }
+ rest, ok := strings.CutPrefix(string(raw), "gitdir:")
+ if !ok {
+ return false
+ }
+ gitdir := strings.TrimSpace(rest)
+ if gitdir == "" {
+ return false
+ }
+ if !filepath.IsAbs(gitdir) {
+ gitdir = filepath.Join(filepath.Dir(path), gitdir)
+ }
+ return isDir(gitdir)
}
type vcsNotFoundError struct {
diff --git a/src/cmd/go/internal/vcs/vcs_test.go b/src/cmd/go/internal/vcs/vcs_test.go
index 361d85b..5b66b95 100644
--- a/src/cmd/go/internal/vcs/vcs_test.go
+++ b/src/cmd/go/internal/vcs/vcs_test.go
@@ -6,7 +6,6 @@
import (
"errors"
- "fmt"
"internal/testenv"
"os"
"path/filepath"
@@ -215,40 +214,61 @@
// Test that vcs.FromDir correctly inspects a given directory and returns the
// right VCS and repo directory.
func TestFromDir(t *testing.T) {
- tempDir := t.TempDir()
-
- for _, vcs := range vcsList {
- for r, root := range vcs.RootNames {
- vcsName := fmt.Sprint(vcs.Name, r)
- dir := filepath.Join(tempDir, "example.com", vcsName, root.filename)
- if root.isDir {
- err := os.MkdirAll(dir, 0755)
- if err != nil {
- t.Fatal(err)
- }
- } else {
- err := os.MkdirAll(filepath.Dir(dir), 0755)
- if err != nil {
- t.Fatal(err)
- }
- f, err := os.Create(dir)
- if err != nil {
- t.Fatal(err)
- }
- f.Close()
- }
-
- wantRepoDir := filepath.Dir(dir)
- gotRepoDir, gotVCS, err := FromDir(dir, tempDir)
- if err != nil {
- t.Errorf("FromDir(%q, %q): %v", dir, tempDir, err)
- continue
- }
- if gotRepoDir != wantRepoDir || gotVCS.Name != vcs.Name {
- t.Errorf("FromDir(%q, %q) = RepoDir(%s), VCS(%s); want RepoDir(%s), VCS(%s)", dir, tempDir, gotRepoDir, gotVCS.Name, wantRepoDir, vcs.Name)
- }
- }
+ tests := []struct {
+ name string
+ vcs string
+ root string
+ create func(path string) error
+ }{
+ {"hg", "Mercurial", ".hg", mkdir},
+ {"git_dir", "Git", ".git", mkdir},
+ {"git_worktree", "Git", ".git", createGitWorktreeFile},
+ {"bzr", "Bazaar", ".bzr", mkdir},
+ {"svn", "Subversion", ".svn", mkdir},
+ {"fossil_fslckout", "Fossil", ".fslckout", touch},
+ {"fossil_FOSSIL_", "Fossil", "_FOSSIL_", touch},
}
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ tempDir := t.TempDir()
+ repoDir := filepath.Join(tempDir, "example.com")
+ if err := mkdir(repoDir); err != nil {
+ t.Fatal(err)
+ }
+ rootPath := filepath.Join(repoDir, tt.root)
+ if err := tt.create(rootPath); err != nil {
+ t.Fatal(err)
+ }
+ gotRepoDir, gotVCS, err := FromDir(repoDir, tempDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if gotRepoDir != repoDir {
+ t.Errorf("RepoDir = %q, want %q", gotRepoDir, repoDir)
+ }
+ if gotVCS.Name != tt.vcs {
+ t.Errorf("VCS = %q, want %q", gotVCS.Name, tt.vcs)
+ }
+ })
+ }
+}
+
+func mkdir(path string) error {
+ return os.Mkdir(path, 0o755)
+}
+
+func touch(path string) error {
+ return os.WriteFile(path, nil, 0o644)
+}
+
+func createGitWorktreeFile(path string) error {
+ gitdir := path + ".worktree"
+ // gitdir must point to a real directory
+ if err := mkdir(gitdir); err != nil {
+ return err
+ }
+ return os.WriteFile(path, []byte("gitdir: "+gitdir+"\n"), 0o644)
}
func TestIsSecure(t *testing.T) {
diff --git a/src/cmd/go/testdata/script/version_buildvcs_git_worktree.txt b/src/cmd/go/testdata/script/version_buildvcs_git_worktree.txt
new file mode 100644
index 0000000..651d169
--- /dev/null
+++ b/src/cmd/go/testdata/script/version_buildvcs_git_worktree.txt
@@ -0,0 +1,46 @@
+# Test that 'go build' stamps VCS information when building from a git worktree.
+# See https://go.dev/issue/58218.
+
+[!git] skip
+[short] skip
+
+# Create repo with a commit.
+cd repo
+exec git init
+exec git config user.email g.o.p...@go.dev
+exec git config user.name Gopher
+exec git add -A
+exec git commit -m 'initial commit'
+
+# Sanity check: building from main repo includes VCS info.
+go build -o main.exe .
+go version -m main.exe
+stdout '^\tbuild\tvcs=git$'
+stdout '^\tbuild\tvcs.modified=false$'
+
+# Create a worktree and build from it.
+exec git worktree add ../worktree HEAD
+cd ../worktree
+go build -o worktree.exe .
+go version -m worktree.exe
+stdout '^\tbuild\tvcs=git$'
+stdout '^\tbuild\tvcs.modified=false$'
+
+# Verify that vcs.modified is detected in the worktree.
+cp ../changed.go a.go
+go build -o modified.exe .
+go version -m modified.exe
+stdout '^\tbuild\tvcs.modified=true$'
+
+-- repo/go.mod --
+module example.com/worktree
+
+go 1.18
+-- repo/a.go --
+package main
+
+func main() {}
+-- changed.go --
+package main
+
+func main() { _ = 1 }
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
os.MkdirAll(dir, 0o777) // Ignore errors — if unsuccessful, the command will likely fail.Nit: minor cleanups like this should generally be in different CLs.
isRoot func(path string) bool // isRoot reports whether path signifies a VCS rootYour code is a more or less straightforward step from the existing code, but consider something like
type isVCSRoot interface {
isRoot(dir string) bool
}
type vcsFileRoot string
func (vfr vcsFileRoot) isRoot(dir string) {
fi, err := os.Stat(filepath.Join(dir, string(vfr)))
return err == nil && fi.Mode().IsRegular()
}
type vcsDirRoot string
func (vfd vcsDirRoot) isRoot(dir string) {
fi, err := os.Stat(filepath.Join(dir, string(vfd)))
return err == nil && fi.IsDir()
}
Then above write things like
var vcsFossil = ...
[]isVCSRoot{
vcsFileRoot(".fslckout"),
vcsFileRoot("_FOSSIL_"),
}
and
func isVCSRoot(dir string, roots []isVCSRoot) bool {
for _, root := range roots {
if root.isRoot(dir) {
return true
}
}
return false
}| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
os.MkdirAll(dir, 0o777) // Ignore errors — if unsuccessful, the command will likely fail.Nit: minor cleanups like this should generally be in different CLs.
done, CL 736440
isRoot func(path string) bool // isRoot reports whether path signifies a VCS rootYour code is a more or less straightforward step from the existing code, but consider something like
type isVCSRoot interface {
isRoot(dir string) bool
}
type vcsFileRoot string
func (vfr vcsFileRoot) isRoot(dir string) {
fi, err := os.Stat(filepath.Join(dir, string(vfr)))
return err == nil && fi.Mode().IsRegular()
}
type vcsDirRoot string
func (vfd vcsDirRoot) isRoot(dir string) {
fi, err := os.Stat(filepath.Join(dir, string(vfd)))
return err == nil && fi.IsDir()
}Then above write things like
var vcsFossil = ...
[]isVCSRoot{
vcsFileRoot(".fslckout"),
vcsFileRoot("_FOSSIL_"),
}and
func isVCSRoot(dir string, roots []isVCSRoot) bool {
for _, root := range roots {
if root.isRoot(dir) {
return true
}
}
return false
}
Done. I adjusted the naming a bit to avoid collisions and improve clarity.
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
| Code-Review | +2 |
| Commit-Queue | +1 |
Thanks.
os.MkdirAll(dir, 0o777) // Ignore errors — if unsuccessful, the command will likely fail.Josh Bleecher SnyderNit: minor cleanups like this should generally be in different CLs.
done, CL 736440
Acknowledged
isRoot func(path string) bool // isRoot reports whether path signifies a VCS rootJosh Bleecher SnyderYour code is a more or less straightforward step from the existing code, but consider something like
type isVCSRoot interface {
isRoot(dir string) bool
}
type vcsFileRoot string
func (vfr vcsFileRoot) isRoot(dir string) {
fi, err := os.Stat(filepath.Join(dir, string(vfr)))
return err == nil && fi.Mode().IsRegular()
}
type vcsDirRoot string
func (vfd vcsDirRoot) isRoot(dir string) {
fi, err := os.Stat(filepath.Join(dir, string(vfd)))
return err == nil && fi.IsDir()
}Then above write things like
var vcsFossil = ...
[]isVCSRoot{
vcsFileRoot(".fslckout"),
vcsFileRoot("_FOSSIL_"),
}and
func isVCSRoot(dir string, roots []isVCSRoot) bool {
for _, root := range roots {
if root.isRoot(dir) {
return true
}
}
return false
}
Done. I adjusted the naming a bit to avoid collisions and improve clarity.
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
| Code-Review | +1 |
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
| Code-Review | +1 |
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |