Skip to content

Commit c9a4b01

Browse files
author
Bryan C. Mills
committed
cmd/go: in 'go build -o', allow the destination file to exist if it is 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]>
1 parent e9f8d67 commit c9a4b01

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/cmd/go/internal/work/exec.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -1610,12 +1610,12 @@ func (b *Builder) copyFile(dst, src string, perm os.FileMode, force bool) error
16101610

16111611
// Be careful about removing/overwriting dst.
16121612
// Do not remove/overwrite if dst exists and is a directory
1613-
// or a non-object file.
1613+
// or a non-empty non-object file.
16141614
if fi, err := os.Stat(dst); err == nil {
16151615
if fi.IsDir() {
16161616
return fmt.Errorf("build output %q already exists and is a directory", dst)
16171617
}
1618-
if !force && fi.Mode().IsRegular() && !isObject(dst) {
1618+
if !force && fi.Mode().IsRegular() && fi.Size() != 0 && !isObject(dst) {
16191619
return fmt.Errorf("build output %q already exists and is not an object file", dst)
16201620
}
16211621
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[short] skip
2+
3+
# Ensure that the target of 'go build -o' can be an existing, empty file so that
4+
# its name can be reserved using ioutil.TempFile or the 'mktemp` command.
5+
6+
go build -o empty-file$GOEXE main.go
7+
8+
-- main.go --
9+
package main
10+
func main() {}
11+
-- empty-file$GOEXE --

0 commit comments

Comments
 (0)