github.com/MetalBlockchain/metalgo@v1.11.9/utils/filesystem/rename.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package filesystem
     5  
     6  import (
     7  	"errors"
     8  	"io/fs"
     9  	"os"
    10  )
    11  
    12  // Renames the file "a" to "b" iff "a" exists.
    13  // It returns "true" and no error, if rename were successful.
    14  // It returns "false" and no error, if the file "a" does not exist.
    15  // It returns "false" and an error, if rename failed.
    16  func RenameIfExists(a, b string) (renamed bool, err error) {
    17  	err = os.Rename(a, b)
    18  	renamed = err == nil
    19  	if errors.Is(err, fs.ErrNotExist) {
    20  		err = nil
    21  	}
    22  	return renamed, err
    23  }