github.com/taubyte/tau-cli@v0.1.13-0.20240326000942-487f0d57edfc/singletons/templates/clone.go (about) 1 package templates 2 3 import ( 4 "errors" 5 "os" 6 "path" 7 "strings" 8 9 git "github.com/taubyte/go-simple-git" 10 "github.com/taubyte/tau-cli/states" 11 ) 12 13 // Template root will give the location of the template and clone 14 // if needed, ex /tmp/taubyte_templates/websites/tb_angular_template 15 func (info *TemplateInfo) templateRoot() (string, error) { 16 if len(info.URL) == 0 { 17 return "", errors.New("template URL not set") 18 } 19 20 // split on / and get final item for the name 21 splitName := strings.Split(info.URL, "/") 22 cloneFrom := path.Join(templateFolder, splitName[len(splitName)-1]) 23 24 // open or clone the repository 25 _, err := git.New(states.Context, 26 git.Root(cloneFrom), 27 git.URL(info.URL), 28 ) 29 if err != nil { 30 return "", err 31 } 32 33 return cloneFrom, nil 34 } 35 36 // CloneTo will create the directory for the template and move 37 // all files from the template repository except .git 38 func (info *TemplateInfo) CloneTo(dir string) error { 39 root, err := info.templateRoot() 40 if err != nil { 41 return err 42 } 43 44 // copy all files from root to dir except `.git` 45 err = copyFiles(root, dir, func(f os.DirEntry) bool { 46 return f.Name() != ".git" 47 }) 48 if err != nil { 49 return err 50 } 51 52 return nil 53 } 54 55 func copyFiles(src, dst string, filter func(f os.DirEntry) bool) error { 56 files, err := os.ReadDir(src) 57 if err != nil { 58 return err 59 } 60 61 for _, f := range files { 62 if !filter(f) { 63 continue 64 } 65 66 srcFile := path.Join(src, f.Name()) 67 dstFile := path.Join(dst, f.Name()) 68 69 if f.IsDir() { 70 err = os.MkdirAll(dstFile, 0755) 71 if err != nil { 72 return err 73 } 74 75 err = copyFiles(srcFile, dstFile, filter) 76 if err != nil { 77 return err 78 } 79 } else { 80 err = copyFile(srcFile, dstFile) 81 if err != nil { 82 return err 83 } 84 } 85 } 86 87 return nil 88 } 89 90 func copyFile(src string, dst string) error { 91 srcData, err := os.ReadFile(src) 92 if err != nil { 93 return err 94 } 95 96 return os.WriteFile(dst, srcData, 0755) 97 }