Skip to content

Commit

Permalink
cmd/go: prevent go work use panic when given a file
Browse files Browse the repository at this point in the history
The current implementation fails to identify that an argument to go work
use is a file when expecting a directory, and panics when attempting to
access it as a directory. This change checks arguments are directories
and generates an error otherwise.

Fixes #51749

Change-Id: If8f69d233409e93fcf391a8774bace74c031c986
Reviewed-on: https://go-review.googlesource.com/c/go/+/393615
Reviewed-by: Bryan Mills <bcmills@google.com>
Trust: Bryan Mills <bcmills@google.com>
Run-TryBot: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Trust: Ian Lance Taylor <iant@golang.org>
  • Loading branch information
John Anthony authored and Bryan Mills committed Mar 31, 2022
1 parent 31ee4bb commit a84ef50
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/cmd/go/internal/workcmd/use.go
Expand Up @@ -85,13 +85,14 @@ func runUse(ctx context.Context, cmd *base.Command, args []string) {
lookDir := func(dir string) {
absDir, dir := pathRel(workDir, dir)

fi, err := os.Stat(filepath.Join(absDir, "go.mod"))
fi, err := fsys.Stat(filepath.Join(absDir, "go.mod"))
if err != nil {
if os.IsNotExist(err) {
keepDirs[absDir] = ""
return
} else {
base.Errorf("go: %v", err)
}
base.Errorf("go: %v", err)
return
}

if !fi.Mode().IsRegular() {
Expand All @@ -109,7 +110,11 @@ func runUse(ctx context.Context, cmd *base.Command, args []string) {
}
for _, useDir := range args {
if !*useR {
lookDir(useDir)
if target, err := fsys.Stat(useDir); err == nil && !target.IsDir() {
base.Errorf(`go: argument "%s" is not a directory`, useDir)
} else {
lookDir(useDir)
}
continue
}

Expand Down
12 changes: 12 additions & 0 deletions src/cmd/go/testdata/script/work_use_file.txt
@@ -0,0 +1,12 @@
cp go.work go.work.orig

# If an argument to 'go work use' is a file it should be handled gracefully as
# an error and go.work should not be modified
! go work use foo.txt
stderr '^go: argument "foo\.txt" is not a directory$'
cmp go.work go.work.orig


-- go.work --
go 1.18
-- foo.txt --

0 comments on commit a84ef50

Please sign in to comment.