github.com/remind101/go-getter@v0.0.0-20180809191950-4bda8fa99001/get_file_unix.go (about) 1 // +build !windows 2 3 package getter 4 5 import ( 6 "fmt" 7 "io" 8 "net/url" 9 "os" 10 "path/filepath" 11 ) 12 13 func (g *FileGetter) Get(dst string, u *url.URL) error { 14 path := u.Path 15 if u.RawPath != "" { 16 path = u.RawPath 17 } 18 19 // The source path must exist and be a directory to be usable. 20 if fi, err := os.Stat(path); err != nil { 21 return fmt.Errorf("source path error: %s", err) 22 } else if !fi.IsDir() { 23 return fmt.Errorf("source path must be a directory") 24 } 25 26 fi, err := os.Lstat(dst) 27 if err != nil && !os.IsNotExist(err) { 28 return err 29 } 30 31 // If the destination already exists, it must be a symlink 32 if err == nil { 33 mode := fi.Mode() 34 if mode&os.ModeSymlink == 0 { 35 return fmt.Errorf("destination exists and is not a symlink") 36 } 37 38 // Remove the destination 39 if err := os.Remove(dst); err != nil { 40 return err 41 } 42 } 43 44 // Create all the parent directories 45 if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil { 46 return err 47 } 48 49 return os.Symlink(path, dst) 50 } 51 52 func (g *FileGetter) GetFile(dst string, u *url.URL) error { 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 if fi, err := os.Stat(path); err != nil { 60 return fmt.Errorf("source path error: %s", err) 61 } else if fi.IsDir() { 62 return fmt.Errorf("source path must be a file") 63 } 64 65 _, err := os.Lstat(dst) 66 if err != nil && !os.IsNotExist(err) { 67 return err 68 } 69 70 // If the destination already exists, it must be a symlink 71 if err == nil { 72 // Remove the destination 73 if err := os.Remove(dst); err != nil { 74 return err 75 } 76 } 77 78 // Create all the parent directories 79 if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil { 80 return err 81 } 82 83 // If we're not copying, just symlink and we're done 84 if !g.Copy { 85 return os.Symlink(path, dst) 86 } 87 88 // Copy 89 srcF, err := os.Open(path) 90 if err != nil { 91 return err 92 } 93 defer srcF.Close() 94 95 dstF, err := os.Create(dst) 96 if err != nil { 97 return err 98 } 99 defer dstF.Close() 100 101 _, err = io.Copy(dstF, srcF) 102 return err 103 }