Skip to content

Commit

Permalink
cmd/go: in 'go build -o', allow the destination file to exist if it i…
Browse files Browse the repository at this point in the history
…s empty

This allows the target of 'go build' to be a filename constructed
using ioutil.TempFile or similar, without racily deleting the file
before rebuilding it.

Updates #32407
Updates #28387

Change-Id: I4c5072830a02b93f0c4186b50bffa9de00257afe
Reviewed-on: https://go-review.googlesource.com/c/go/+/206477
Run-TryBot: Bryan C. Mills <[email protected]>
Reviewed-by: Jay Conrod <[email protected]>
  • Loading branch information
Bryan C. Mills committed Nov 11, 2019
1 parent e9f8d67 commit c9a4b01
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/cmd/go/internal/work/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -1610,12 +1610,12 @@ func (b *Builder) copyFile(dst, src string, perm os.FileMode, force bool) error

// Be careful about removing/overwriting dst.
// Do not remove/overwrite if dst exists and is a directory
// or a non-object file.
// or a non-empty non-object file.
if fi, err := os.Stat(dst); err == nil {
if fi.IsDir() {
return fmt.Errorf("build output %q already exists and is a directory", dst)
}
if !force && fi.Mode().IsRegular() && !isObject(dst) {
if !force && fi.Mode().IsRegular() && fi.Size() != 0 && !isObject(dst) {
return fmt.Errorf("build output %q already exists and is not an object file", dst)
}
}
Expand Down
11 changes: 11 additions & 0 deletions src/cmd/go/testdata/script/test_compile_tempfile.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[short] skip

# Ensure that the target of 'go build -o' can be an existing, empty file so that
# its name can be reserved using ioutil.TempFile or the 'mktemp` command.

go build -o empty-file$GOEXE main.go

-- main.go --
package main
func main() {}
-- empty-file$GOEXE --

0 comments on commit c9a4b01

Please sign in to comment.