github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/file/open_windows.go (about) 1 // Copyright 2021 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //go:build windows 16 // +build windows 17 18 package file 19 20 import ( 21 "os" 22 "syscall" 23 "time" 24 25 "golang.org/x/sys/windows" 26 ) 27 28 // Rename functions exactly like os.Rename, except that it retries upon failure on Windows. This "fixes" some errors 29 // that appear on Windows. 30 func Rename(oldpath, newpath string) error { 31 err := os.Rename(oldpath, newpath) 32 if isAccessError(err) { 33 for waitTime := time.Duration(1); isAccessError(err) && waitTime <= 10000; waitTime *= 10 { 34 time.Sleep(waitTime * time.Millisecond) 35 err = os.Rename(oldpath, newpath) 36 } 37 } 38 return err 39 } 40 41 // Remove functions exactly like os.Remove, except that it retries upon failure on Windows. This "fixes" some errors 42 // that appear on Windows. 43 func Remove(name string) error { 44 err := os.Remove(name) 45 if isAccessError(err) { 46 for waitTime := time.Duration(1); isAccessError(err) && waitTime <= 10000; waitTime *= 10 { 47 time.Sleep(waitTime * time.Millisecond) 48 err = os.Remove(name) 49 } 50 } 51 return err 52 } 53 54 // RemoveAll functions exactly like os.RemoveAll, except that it retries upon failure on Windows. This "fixes" some errors 55 // that appear on Windows. 56 func RemoveAll(path string) error { 57 err := os.RemoveAll(path) 58 if isAccessError(err) { 59 for waitTime := time.Duration(1); isAccessError(err) && waitTime <= 10000; waitTime *= 10 { 60 time.Sleep(waitTime * time.Millisecond) 61 err = os.RemoveAll(path) 62 } 63 } 64 return err 65 } 66 67 func isAccessError(err error) bool { 68 switch err := err.(type) { 69 case *os.LinkError: 70 sysErr, ok := err.Err.(syscall.Errno) 71 if ok && (sysErr == windows.ERROR_ACCESS_DENIED || sysErr == windows.ERROR_SHARING_VIOLATION) { 72 return true 73 } 74 case *os.PathError: 75 sysErr, ok := err.Err.(syscall.Errno) 76 if ok && (sysErr == windows.ERROR_ACCESS_DENIED || sysErr == windows.ERROR_SHARING_VIOLATION) { 77 return true 78 } 79 case *os.SyscallError: 80 sysErr, ok := err.Err.(syscall.Errno) 81 if ok && (sysErr == windows.ERROR_ACCESS_DENIED || sysErr == windows.ERROR_SHARING_VIOLATION) { 82 return true 83 } 84 } 85 return false 86 }