github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/fileutil/move.go (about) 1 // Copyright 2019 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package fileutil 12 13 import ( 14 "os" 15 16 "github.com/cockroachdb/cockroach/pkg/util/sysutil" 17 "github.com/cockroachdb/errors" 18 ) 19 20 // Move moves a file from a directory to another, while handling 21 // cross-filesystem moves properly. 22 // If the target file already exists, it is truncated. 23 // If the move fails, then the target file may be left in an inconsistent state. 24 func Move(oldPath, newPath string) error { 25 err := os.Rename(oldPath, newPath) 26 if !isCrossDeviceLinkError(err) { 27 return err 28 } 29 30 if err = CopyFile(oldPath, newPath); err != nil { 31 return err 32 } 33 34 return os.RemoveAll(oldPath) 35 } 36 37 func isCrossDeviceLinkError(err error) bool { 38 if err == nil { 39 return false 40 } 41 var le *os.LinkError 42 if errors.As(err, &le) { 43 return sysutil.IsCrossDeviceLinkErrno(le.Err) 44 } 45 return false 46 }