github.com/paketo-buildpacks/libpak@v1.70.0/sherpa/copy_file.go (about)

     1  /*
     2   * Copyright 2018-2020 the original author or 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   *      https://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 sherpa
    18  
    19  import (
    20  	"fmt"
    21  	"io"
    22  	"os"
    23  	"path/filepath"
    24  )
    25  
    26  // CopyFile copies a file from the source to the destination. It ensures that the parent directory is created and
    27  // matches the source and destination permissions.
    28  func CopyFile(source *os.File, destination string) error {
    29  	s, err := source.Stat()
    30  	if err != nil {
    31  		return fmt.Errorf("unable to stat %s\n%w", source.Name(), err)
    32  	}
    33  
    34  	file := filepath.Dir(destination)
    35  	if err := os.MkdirAll(file, 0755); err != nil {
    36  		return fmt.Errorf("unable to create directory %s\n%w", file, err)
    37  	}
    38  
    39  	out, err := os.OpenFile(destination, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, s.Mode())
    40  	if err != nil {
    41  		return fmt.Errorf("unable to open %s\n%w", destination, err)
    42  	}
    43  	defer out.Close()
    44  
    45  	if _, err := io.Copy(out, source); err != nil {
    46  		return fmt.Errorf("unable to copy from %s to %s\n%w", source.Name(), destination, err)
    47  	}
    48  
    49  	return nil
    50  }