github.com/SupersunnySea/draft@v0.16.0/pkg/draft/pack/load.go (about) 1 package pack 2 3 import ( 4 "fmt" 5 "io" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 10 "k8s.io/helm/pkg/chartutil" 11 ) 12 13 // FromDir takes a string name, tries to resolve it to a file or directory, and then loads it. 14 // 15 // This is the preferred way to load a pack. It will discover the pack encoding 16 // and hand off to the appropriate pack reader. 17 func FromDir(dir string) (*Pack, error) { 18 pack := new(Pack) 19 pack.Files = make(map[string]io.ReadCloser) 20 21 topdir, err := filepath.Abs(dir) 22 if err != nil { 23 return nil, err 24 } 25 26 pack.Chart, err = chartutil.LoadDir(filepath.Join(topdir, ChartsDir)) 27 if err != nil { 28 return nil, err 29 } 30 31 files, err := ioutil.ReadDir(topdir) 32 if err != nil { 33 return nil, fmt.Errorf("error reading %s: %s", topdir, err) 34 } 35 36 // load all files in pack directory 37 for _, fInfo := range files { 38 if !fInfo.IsDir() { 39 f, err := os.Open(filepath.Join(topdir, fInfo.Name())) 40 if err != nil { 41 return nil, err 42 } 43 if fInfo.Name() != "README.md" { 44 pack.Files[fInfo.Name()] = f 45 } 46 } else { 47 if fInfo.Name() != "charts" { 48 packFiles, err := extractFiles(filepath.Join(topdir, fInfo.Name()), "") 49 if err != nil { 50 return nil, err 51 } 52 for k, v := range packFiles { 53 pack.Files[k] = v 54 } 55 } 56 } 57 } 58 59 return pack, nil 60 } 61 62 func extractFiles(dir, base string) (map[string]io.ReadCloser, error) { 63 baseDir := filepath.Join(base, filepath.Base(dir)) 64 packFiles := make(map[string]io.ReadCloser) 65 66 absDir, err := filepath.Abs(dir) 67 if err != nil { 68 return nil, err 69 } 70 71 files, err := ioutil.ReadDir(absDir) 72 if err != nil { 73 return packFiles, fmt.Errorf("error reading %s: %s", dir, err) 74 } 75 76 for _, fInfo := range files { 77 if !fInfo.IsDir() { 78 fPath := filepath.Join(dir, fInfo.Name()) 79 f, err := os.Open(fPath) 80 if err != nil { 81 return nil, err 82 } 83 packFiles[filepath.Join(baseDir, fInfo.Name())] = f 84 } else { 85 nestedPackFiles, err := extractFiles(filepath.Join(dir, fInfo.Name()), baseDir) 86 if err != nil { 87 return nil, err 88 } 89 for k, v := range nestedPackFiles { 90 packFiles[k] = v 91 } 92 } 93 } 94 return packFiles, nil 95 }