gitee.com/h79/goutils@v1.22.10/build/copy.go (about) 1 package build 2 3 import ( 4 "fmt" 5 "gitee.com/h79/goutils/common/archive" 6 fileconfig "gitee.com/h79/goutils/common/file/config" 7 "io" 8 "os" 9 "path/filepath" 10 ) 11 12 type copyBuilder struct { 13 } 14 15 func (t *copyBuilder) Ext() string { 16 return "" 17 } 18 19 func (*copyBuilder) New(w io.WriteCloser, conf archive.Config) archive.Archive { 20 return ©Archive{Path: conf.Path} 21 } 22 23 func (*copyBuilder) Coping(r *os.File, w io.Writer, conf archive.Config) (archive.Archive, error) { 24 return nil, fmt.Errorf("not support") 25 } 26 27 type copyArchive struct { 28 Path string 29 } 30 31 func (c *copyArchive) Close() error { 32 return nil 33 } 34 35 func (c *copyArchive) Add(f fileconfig.File, stream ...fileconfig.ReaderStream) error { 36 info, err := os.Lstat(f.Source) // #nosec 37 if err != nil { 38 return fmt.Errorf("%s: %w", f.Source, err) 39 } 40 filename := filepath.Join(c.Path, f.Destination) 41 if info.IsDir() { 42 return os.Mkdir(filename, f.Info.Mode) 43 } 44 _ = os.MkdirAll(filepath.Dir(filename), f.Info.Mode) 45 // Open the file and create a new one 46 r, err := os.Open(f.Source) 47 if err != nil { 48 return err 49 } 50 defer func(r *os.File) { 51 err = r.Close() 52 if err != nil { 53 } 54 }(r) 55 56 w, err := os.Create(filename) 57 if err != nil { 58 return err 59 } 60 defer func(w *os.File) { 61 err = w.Close() 62 if err != nil { 63 } 64 }(w) 65 66 // Copy the content 67 _, err = io.Copy(w, r) 68 if err != nil { 69 return err 70 } 71 if err != nil { 72 return err 73 } 74 for i := range stream { 75 stream[i].OnReader(r) 76 } 77 return nil 78 }