github.com/0xPolygon/supernets2-node@v0.0.0-20230711153321-2fe574524eaa/test/scripts/cmd/dependencies/files.go (about) 1 package dependencies 2 3 import ( 4 "io" 5 "os" 6 "path" 7 "runtime" 8 "strings" 9 10 "github.com/0xPolygon/supernets2-node/log" 11 "github.com/spf13/afero" 12 ) 13 14 func updateFiles(fs afero.Fs, sourceDir, targetDir string) error { 15 const bufferSize = 20 16 err := afero.Walk(fs, targetDir, func(wpath string, info os.FileInfo, err error) error { 17 if err != nil { 18 return err 19 } 20 if info == nil || info.IsDir() { 21 return nil 22 } 23 relativePath := strings.Replace(wpath, targetDir, "", -1) 24 sourcePath := path.Join(sourceDir, relativePath) 25 26 sourceFile, err := fs.Open(sourcePath) 27 if os.IsNotExist(err) { 28 // we allow source files to not exist, for instance, test vectors that we 29 // have in supernets2-node but are not present in the upstream repo 30 return nil 31 } 32 if err != nil { 33 return err 34 } 35 defer func() { 36 if err := sourceFile.Close(); err != nil { 37 log.Errorf("Could not close %s: %v", sourceFile.Name(), err) 38 } 39 }() 40 targetFile, err := fs.OpenFile(wpath, os.O_RDWR|os.O_TRUNC, 0644) //nolint:gomnd 41 if err != nil { 42 return err 43 } 44 defer func() { 45 if err := targetFile.Close(); err != nil { 46 log.Errorf("Could not close %s: %v", targetFile.Name(), err) 47 } 48 }() 49 buf := make([]byte, bufferSize) 50 for { 51 n, err := sourceFile.Read(buf) 52 if err != nil && err != io.EOF { 53 return err 54 } 55 if n == 0 { 56 break 57 } 58 if _, err := targetFile.Write(buf[:n]); err != nil { 59 return err 60 } 61 } 62 return nil 63 }) 64 return err 65 } 66 67 func getTargetPath(targetPath string) string { 68 if strings.HasPrefix(targetPath, "/") { 69 return targetPath 70 } 71 _, filename, _, _ := runtime.Caller(1) 72 73 return path.Join(path.Dir(filename), targetPath) 74 }