github.com/coreos/mantle@v0.13.0/system/copy.go (about)

     1  // Copyright 2015 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package system
    16  
    17  import (
    18  	"fmt"
    19  	"io"
    20  	"os"
    21  	"path/filepath"
    22  )
    23  
    24  // CopyRegularFile copies a file in place, updates are not atomic. If
    25  // the destination doesn't exist it will be created with the same
    26  // permissions as the original but umask is respected. If the
    27  // destination already exists the permissions will remain as-is.
    28  func CopyRegularFile(src, dest string) (err error) {
    29  	srcFile, err := os.Open(src)
    30  	if err != nil {
    31  		return err
    32  	}
    33  	defer srcFile.Close()
    34  
    35  	srcInfo, err := srcFile.Stat()
    36  	if err != nil {
    37  		return err
    38  	}
    39  	mode := srcInfo.Mode()
    40  	if !mode.IsRegular() {
    41  		return fmt.Errorf("Not a regular file: %s", src)
    42  	}
    43  
    44  	destFile, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
    45  	if err != nil {
    46  		return err
    47  	}
    48  	defer func() {
    49  		e := destFile.Close()
    50  		if err == nil {
    51  			err = e
    52  		}
    53  	}()
    54  
    55  	_, err = io.Copy(destFile, srcFile)
    56  	return err
    57  }
    58  
    59  // InstallRegularFile copies a file, creating any parent directories.
    60  func InstallRegularFile(src, dest string) error {
    61  	destDir := filepath.Dir(dest)
    62  	if err := os.MkdirAll(destDir, 0755); err != nil {
    63  		return err
    64  	}
    65  	return CopyRegularFile(src, dest)
    66  }