github.com/oam-dev/kubevela@v1.9.11/pkg/addon/reader_github.go (about) 1 /* 2 Copyright 2021 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package addon 18 19 import ( 20 "fmt" 21 "path" 22 "strings" 23 24 "github.com/google/go-github/v32/github" 25 "github.com/pkg/errors" 26 27 "github.com/oam-dev/kubevela/pkg/utils" 28 ) 29 30 var _ AsyncReader = &gitReader{} 31 32 // gitHelper helps get addon's file by git 33 type gitHelper struct { 34 Client *github.Client 35 Meta *utils.Content 36 } 37 38 type gitReader struct { 39 h *gitHelper 40 } 41 42 // ListAddonMeta relative path to repoURL/basePath 43 func (g *gitReader) ListAddonMeta() (map[string]SourceMeta, error) { 44 subItems := make(map[string]SourceMeta) 45 _, items, err := g.h.readRepo("") 46 if err != nil { 47 return nil, err 48 } 49 for _, item := range items { 50 // single addon 51 if item.GetType() != DirType { 52 continue 53 } 54 addonName := path.Base(item.GetPath()) 55 addonMeta, err := g.listAddonMeta(g.RelativePath(item)) 56 if err != nil { 57 return nil, errors.Wrapf(err, "fail to get addon meta of %s", addonName) 58 } 59 subItems[addonName] = SourceMeta{Name: addonName, Items: addonMeta} 60 } 61 return subItems, nil 62 } 63 64 func (g *gitReader) listAddonMeta(dirPath string) ([]Item, error) { 65 _, items, err := g.h.readRepo(dirPath) 66 if err != nil { 67 return nil, err 68 } 69 res := make([]Item, 0) 70 for _, item := range items { 71 switch item.GetType() { 72 case FileType: 73 res = append(res, item) 74 case DirType: 75 subItems, err := g.listAddonMeta(g.RelativePath(item)) 76 if err != nil { 77 return nil, err 78 } 79 res = append(res, subItems...) 80 } 81 } 82 return res, nil 83 } 84 85 // ReadFile read file content from github 86 func (g *gitReader) ReadFile(relativePath string) (content string, err error) { 87 file, _, err := g.h.readRepo(relativePath) 88 if err != nil { 89 return 90 } 91 if file == nil { 92 return "", fmt.Errorf("path %s is not a file", relativePath) 93 } 94 return file.GetContent() 95 } 96 97 func (g *gitReader) RelativePath(item Item) string { 98 absPath := strings.Split(item.GetPath(), "/") 99 if g.h.Meta.GithubContent.Path == "" { 100 return path.Join(absPath...) 101 } 102 base := strings.Split(g.h.Meta.GithubContent.Path, "/") 103 return path.Join(absPath[len(base):]...) 104 }