github.com/annwntech/go-micro/v2@v2.9.5/runtime/local/source/git/git.go (about) 1 // Package git provides a git source 2 package git 3 4 import ( 5 "os" 6 "path/filepath" 7 "strings" 8 9 "github.com/go-git/go-git/v5" 10 "github.com/annwntech/go-micro/v2/runtime/local/source" 11 ) 12 13 // Source retrieves source code 14 // An empty struct can be used 15 type Source struct { 16 Options source.Options 17 } 18 19 func (g *Source) Fetch(url string) (*source.Repository, error) { 20 purl := url 21 22 if parts := strings.Split(url, "://"); len(parts) > 1 { 23 purl = parts[len(parts)-1] 24 } 25 26 name := filepath.Base(url) 27 path := filepath.Join(g.Options.Path, purl) 28 29 _, err := git.PlainClone(path, false, &git.CloneOptions{ 30 URL: url, 31 }) 32 if err == nil { 33 return &source.Repository{ 34 Name: name, 35 Path: path, 36 URL: url, 37 }, nil 38 } 39 40 // repo already exists 41 if err != git.ErrRepositoryAlreadyExists { 42 return nil, err 43 } 44 45 // open repo 46 re, err := git.PlainOpen(path) 47 if err != nil { 48 return nil, err 49 } 50 51 // update it 52 if err := re.Fetch(nil); err != nil { 53 return nil, err 54 } 55 56 return &source.Repository{ 57 Name: name, 58 Path: path, 59 URL: url, 60 }, nil 61 } 62 63 func (g *Source) Commit(r *source.Repository) error { 64 repo := filepath.Join(r.Path) 65 re, err := git.PlainOpen(repo) 66 if err != nil { 67 return err 68 } 69 return re.Push(nil) 70 } 71 72 func (g *Source) String() string { 73 return "git" 74 } 75 76 func NewSource(opts ...source.Option) *Source { 77 options := source.Options{ 78 Path: os.TempDir(), 79 } 80 for _, o := range opts { 81 o(&options) 82 } 83 84 return &Source{ 85 Options: options, 86 } 87 }