github.com/paketo-buildpacks/libpak@v1.70.0/internal/entry_writer.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 internal
    18  
    19  import (
    20  	"fmt"
    21  	"io"
    22  	"os"
    23  	"path/filepath"
    24  )
    25  
    26  const ModeExecutable = 0100
    27  
    28  type EntryWriter struct{}
    29  
    30  func (e EntryWriter) Write(source string, destination string) error {
    31  	p := filepath.Dir(destination)
    32  	if err := os.MkdirAll(p, 0755); err != nil {
    33  		return fmt.Errorf("unable to create destination directory %s\n%w", p, err)
    34  	}
    35  
    36  	s, err := os.Lstat(source)
    37  	if err != nil {
    38  		return fmt.Errorf("unable to stat file %s\n%w", source, err)
    39  	}
    40  
    41  	if s.Mode()&os.ModeSymlink != 0 {
    42  		target, err := os.Readlink(source)
    43  		if err != nil {
    44  			return fmt.Errorf("unable to read link %s\n%w", source, err)
    45  		}
    46  
    47  		if err := os.Symlink(target, destination); err != nil {
    48  			return fmt.Errorf("unable to create link %s\n%w", destination, err)
    49  		}
    50  
    51  		return nil
    52  	}
    53  
    54  	var perm os.FileMode
    55  	if s.Mode()&ModeExecutable == ModeExecutable {
    56  		perm = 0755
    57  	} else {
    58  		perm = 0644
    59  	}
    60  
    61  	in, err := os.OpenFile(source, os.O_RDONLY, 0)
    62  	if err != nil {
    63  		return fmt.Errorf("unable to open source file %s\n%w", source, err)
    64  	}
    65  	defer in.Close()
    66  
    67  	out, err := os.OpenFile(destination, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, perm)
    68  	if err != nil {
    69  		return fmt.Errorf("unable to open destination file %s\n%w", destination, err)
    70  	}
    71  	defer out.Close()
    72  
    73  	if _, err := io.Copy(out, in); err != nil {
    74  		return fmt.Errorf("unable to copy %s to %s\n%w", source, destination, err)
    75  	}
    76  
    77  	return nil
    78  }