...

Source file src/helm.sh/helm/v3/internal/fileutil/fileutil.go

Documentation: helm.sh/helm/v3/internal/fileutil

     1  /*
     2  Copyright The Helm 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 fileutil
    18  
    19  import (
    20  	"io"
    21  	"os"
    22  	"path/filepath"
    23  
    24  	"helm.sh/helm/v3/internal/third_party/dep/fs"
    25  )
    26  
    27  // AtomicWriteFile atomically (as atomic as os.Rename allows) writes a file to a
    28  // disk.
    29  func AtomicWriteFile(filename string, reader io.Reader, mode os.FileMode) error {
    30  	tempFile, err := os.CreateTemp(filepath.Split(filename))
    31  	if err != nil {
    32  		return err
    33  	}
    34  	tempName := tempFile.Name()
    35  
    36  	if _, err := io.Copy(tempFile, reader); err != nil {
    37  		tempFile.Close() // return value is ignored as we are already on error path
    38  		return err
    39  	}
    40  
    41  	if err := tempFile.Close(); err != nil {
    42  		return err
    43  	}
    44  
    45  	if err := os.Chmod(tempName, mode); err != nil {
    46  		return err
    47  	}
    48  
    49  	return fs.RenameWithFallback(tempName, filename)
    50  }
    51  

View as plain text