github.com/weiwenhao/getter@v1.30.1/get_file_unix.go (about)

     1  // +build !windows
     2  
     3  package getter
     4  
     5  import (
     6  	"fmt"
     7  	"net/url"
     8  	"os"
     9  	"path/filepath"
    10  )
    11  
    12  func (g *FileGetter) Get(dst string, u *url.URL) error {
    13  	path := u.Path
    14  	if u.RawPath != "" {
    15  		path = u.RawPath
    16  	}
    17  
    18  	// The source path must exist and be a directory to be usable.
    19  	if fi, err := os.Stat(path); err != nil {
    20  		return fmt.Errorf("source path error: %s", err)
    21  	} else if !fi.IsDir() {
    22  		return fmt.Errorf("source path must be a directory")
    23  	}
    24  
    25  	fi, err := os.Lstat(dst)
    26  	if err != nil && !os.IsNotExist(err) {
    27  		return err
    28  	}
    29  
    30  	// If the destination already exists, it must be a symlink
    31  	if err == nil {
    32  		mode := fi.Mode()
    33  		if mode&os.ModeSymlink == 0 {
    34  			return fmt.Errorf("destination exists and is not a symlink")
    35  		}
    36  
    37  		// Remove the destination
    38  		if err := os.Remove(dst); err != nil {
    39  			return err
    40  		}
    41  	}
    42  
    43  	// Create all the parent directories
    44  	if err := os.MkdirAll(filepath.Dir(dst), g.client.mode(0755)); err != nil {
    45  		return err
    46  	}
    47  
    48  	return os.Symlink(path, dst)
    49  }
    50  
    51  func (g *FileGetter) GetFile(dst string, u *url.URL) error {
    52  	ctx := g.Context()
    53  	path := u.Path
    54  	if u.RawPath != "" {
    55  		path = u.RawPath
    56  	}
    57  
    58  	// The source path must exist and be a file to be usable.
    59  	var fi os.FileInfo
    60  	var err error
    61  	if fi, err = os.Stat(path); err != nil {
    62  		return fmt.Errorf("source path error: %s", err)
    63  	} else if fi.IsDir() {
    64  		return fmt.Errorf("source path must be a file")
    65  	}
    66  
    67  	_, err = os.Lstat(dst)
    68  	if err != nil && !os.IsNotExist(err) {
    69  		return err
    70  	}
    71  
    72  	// If the destination already exists, it must be a symlink
    73  	if err == nil {
    74  		// Remove the destination
    75  		if err := os.Remove(dst); err != nil {
    76  			return err
    77  		}
    78  	}
    79  
    80  	// Create all the parent directories
    81  	if err = os.MkdirAll(filepath.Dir(dst), g.client.mode(0755)); err != nil {
    82  		return err
    83  	}
    84  
    85  	// If we're not copying, just symlink and we're done
    86  	if !g.Copy {
    87  		return os.Symlink(path, dst)
    88  	}
    89  
    90  	// Copy
    91  	_, err = copyFile(ctx, dst, path, fi.Mode(), g.client.umask())
    92  	return err
    93  }