github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/internal/smc-devnet/lib/restore.go (about) 1 package lib 2 3 import ( 4 "archive/tar" 5 "compress/gzip" 6 "errors" 7 "io" 8 "os" 9 "path" 10 "strings" 11 12 _ "github.com/SmartMeshFoundation/Spectrum/internal/smc-devnet/statics/statik" 13 "github.com/rakyll/statik/fs" 14 ) 15 16 var ( 17 /* 18 UrlMap = map[string]map[string]string{ 19 "amd64": { 20 "darwin": "/devnet.tar.gz", 21 }, 22 }*/ 23 24 dataUrl = "/devnet.tar.gz" 25 26 ErrorGoarchNotSupport = errors.New("goarch not support") 27 ErrorGoosNotSupport = errors.New("goos not support") 28 dataDir string 29 withoutNodekey bool 30 ) 31 32 func Restore(dir string, reset, masterNode bool) (string, error) { 33 if reset { 34 os.RemoveAll(dir) 35 } 36 os.MkdirAll(dir, 0755) 37 dataDir = dir 38 withoutNodekey = !masterNode 39 return restore() 40 } 41 42 func restore() (string, error) { 43 var binUrl = dataUrl 44 45 /* if m, ok := UrlMap[runtime.GOARCH]; !ok { 46 return "", ErrorGoarchNotSupport 47 } else if url, ok := m[runtime.GOOS]; !ok { 48 return "", ErrorGoosNotSupport 49 } else { 50 binUrl = url[:] 51 }*/ 52 53 if strings.LastIndex(binUrl, "tar.gz") != -1 { 54 err := opentargz(dataDir, binUrl) 55 if err != nil { 56 panic(err) 57 } 58 } 59 return binUrl, nil 60 } 61 62 func opentargz(binDir, binUrl string) error { 63 os.MkdirAll(binDir, 0755) 64 statikFS, err := fs.New() 65 srcFile, err := statikFS.Open(binUrl) 66 if err != nil { 67 return err 68 } 69 defer srcFile.Close() 70 gr, err := gzip.NewReader(srcFile) 71 if err != nil { 72 return err 73 } 74 defer gr.Close() 75 tr := tar.NewReader(gr) 76 for { 77 hdr, err := tr.Next() 78 if err != nil { 79 if err == io.EOF { 80 break 81 } else { 82 return err 83 } 84 } 85 if hdr.FileInfo().IsDir() && strings.Index(hdr.Name, "devnet") == 0 || 86 withoutNodekey && strings.LastIndex(hdr.Name, "nodekey") > 0 { 87 continue 88 } 89 n := strings.Replace(hdr.Name, "devnet/", "", 1) 90 fpath := path.Join(binDir, n) 91 dir, _ := path.Split(fpath) 92 os.MkdirAll(dir, 0755) 93 if !hdr.FileInfo().IsDir() { 94 file, err := os.OpenFile(fpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755) 95 if err != nil { 96 return err 97 } 98 io.Copy(file, tr) 99 } 100 } 101 return nil 102 }