]> Cypherpunks repositories - gostls13.git/commitdiff
os: avoid creating a new file in Truncate on Windows
authorNont Thanonchai <nontkrub@gmail.com>
Wed, 22 Mar 2023 01:04:45 +0000 (01:04 +0000)
committerQuim Muntal <quimmuntal@gmail.com>
Wed, 22 Mar 2023 07:02:33 +0000 (07:02 +0000)
Truncate() a non existent file on Windows currently creates a new blank
file. This behavior is not consistent with other OSes where a file not
found error would instead be returned. This change makes Truncate on
Windows return a file-not-found error when the specified file doesn't
exist, bringing the behavior consistent.

New test cases have been added to prevent a regression.

Fixes #58977

Change-Id: Iaf7b41fc4ea86a2b2ccc59f8be81be42ed211b5c
GitHub-Last-Rev: 636b6c37c1685096281ad506f3cfe35fd5810cb2
GitHub-Pull-Request: golang/go#59085
Reviewed-on: https://go-review.googlesource.com/c/go/+/477215
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Quim Muntal <quimmuntal@gmail.com>
Run-TryBot: Quim Muntal <quimmuntal@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
src/os/file_windows.go
src/os/os_test.go

index e7ee3a56071f6d763fc57980edd69ebae23d4724..7e495069ef7f69ad03b6d0a795323f81b3fc7201 100644 (file)
@@ -160,7 +160,7 @@ func (f *File) seek(offset int64, whence int) (ret int64, err error) {
 // Truncate changes the size of the named file.
 // If the file is a symbolic link, it changes the size of the link's target.
 func Truncate(name string, size int64) error {
-       f, e := OpenFile(name, O_WRONLY|O_CREATE, 0666)
+       f, e := OpenFile(name, O_WRONLY, 0666)
        if e != nil {
                return e
        }
index a8488a11f8c9eed5e575ef678b05dfd7f0ca064a..af6eb705b2e838e747eba3e41862f747d8c12fe5 100644 (file)
@@ -1335,6 +1335,26 @@ func TestTruncate(t *testing.T) {
        }
 }
 
+func TestTruncateNonexistentFile(t *testing.T) {
+       t.Parallel()
+
+       assertPathError := func(t testing.TB, path string, err error) {
+               t.Helper()
+               if pe, ok := err.(*os.PathError); !ok || !os.IsNotExist(err) || pe.Path != path {
+                       t.Errorf("got error: %v\nwant an ErrNotExist PathError with path %q", err, path)
+               }
+       }
+
+       path := filepath.Join(t.TempDir(), "nonexistent")
+
+       err := os.Truncate(path, 1)
+       assertPathError(t, path, err)
+
+       // Truncate shouldn't create any new file.
+       _, err = os.Stat(path)
+       assertPathError(t, path, err)
+}
+
 // Use TempDir (via newFile) to make sure we're on a local file system,
 // so that timings are not distorted by latency and caching.
 // On NFS, timings can be off due to caching of meta-data on