github.com/MetalBlockchain/metalgo@v1.11.9/utils/perms/write_file.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package perms
     5  
     6  import (
     7  	"errors"
     8  	"os"
     9  
    10  	"github.com/google/renameio/v2/maybe"
    11  )
    12  
    13  // WriteFile writes [data] to [filename] and ensures that [filename] has [perm]
    14  // permissions. Will write atomically on linux/macos and fall back to non-atomic
    15  // ioutil.WriteFile on windows.
    16  func WriteFile(filename string, data []byte, perm os.FileMode) error {
    17  	info, err := os.Stat(filename)
    18  	if errors.Is(err, os.ErrNotExist) {
    19  		// The file doesn't exist, so try to write it.
    20  		return maybe.WriteFile(filename, data, perm)
    21  	}
    22  	if err != nil {
    23  		return err
    24  	}
    25  	if info.Mode() != perm {
    26  		// The file currently has the wrong permissions, so update them.
    27  		if err := os.Chmod(filename, perm); err != nil {
    28  			return err
    29  		}
    30  	}
    31  	// The file has the right permissions, so truncate any data and write the
    32  	// file.
    33  	return maybe.WriteFile(filename, data, perm)
    34  }