...

Source file src/github.com/containerd/continuity/ioutils.go

Documentation: github.com/containerd/continuity

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package continuity
    18  
    19  import (
    20  	"bytes"
    21  	"io"
    22  	"os"
    23  	"path/filepath"
    24  )
    25  
    26  // AtomicWriteFile atomically writes data to a file by first writing to a
    27  // temp file and calling rename.
    28  func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error {
    29  	buf := bytes.NewBuffer(data)
    30  	return atomicWriteFile(filename, buf, int64(len(data)), perm)
    31  }
    32  
    33  // atomicWriteFile writes data to a file by first writing to a temp
    34  // file and calling rename.
    35  func atomicWriteFile(filename string, r io.Reader, dataSize int64, perm os.FileMode) error {
    36  	f, err := os.CreateTemp(filepath.Dir(filename), ".tmp-"+filepath.Base(filename))
    37  	if err != nil {
    38  		return err
    39  	}
    40  	needClose := true
    41  	defer func() {
    42  		if needClose {
    43  			f.Close()
    44  		}
    45  	}()
    46  
    47  	err = os.Chmod(f.Name(), perm)
    48  	if err != nil {
    49  		return err
    50  	}
    51  	n, err := io.Copy(f, r)
    52  	if err == nil && n < dataSize {
    53  		return io.ErrShortWrite
    54  	}
    55  	if err != nil {
    56  		return err
    57  	}
    58  	if err = f.Sync(); err != nil {
    59  		return err
    60  	}
    61  
    62  	needClose = false
    63  	if err := f.Close(); err != nil {
    64  		return err
    65  	}
    66  
    67  	return os.Rename(f.Name(), filename)
    68  }
    69  

View as plain text