github.com/richardwilkes/toolbox@v1.121.0/xio/fs/safe/writefile.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package safe
    11  
    12  import (
    13  	"bufio"
    14  	"io"
    15  	"os"
    16  )
    17  
    18  // WriteFile uses writer to write data safely and atomically to a file.
    19  func WriteFile(filename string, writer func(io.Writer) error) (err error) {
    20  	return WriteFileWithMode(filename, writer, 0o644)
    21  }
    22  
    23  // WriteFileWithMode uses writer to write data safely and atomically to a file.
    24  func WriteFileWithMode(filename string, writer func(io.Writer) error, mode os.FileMode) (err error) {
    25  	var f *File
    26  	f, err = CreateWithMode(filename, mode)
    27  	if err != nil {
    28  		return
    29  	}
    30  	w := bufio.NewWriterSize(f, 1<<16)
    31  	defer func() {
    32  		if closeErr := f.Close(); closeErr != nil && err == nil {
    33  			err = closeErr
    34  		}
    35  	}()
    36  	if err = writer(w); err != nil {
    37  		return
    38  	}
    39  	if err = w.Flush(); err != nil {
    40  		return
    41  	}
    42  	if err = f.Commit(); err != nil {
    43  		return
    44  	}
    45  	return
    46  }