-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrepo.go
75 lines (67 loc) · 1.52 KB
/
repo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package pork
import (
"fmt"
"os"
"path/filepath"
"strings"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/config"
"gopkg.in/src-d/go-git.v4/plumbing"
)
type GHRepo struct {
RepoDir string
owner string
project string
repo *git.Repository
}
func NewGHRepo(repository string) (*GHRepo, error) {
values := strings.Split(repository, "/")
if len(values) != 2 {
return nil, fmt.Errorf("repository must be in format owner/project")
}
return &GHRepo{
owner: values[0],
project: values[1],
}, nil
}
func (g *GHRepo) RepositoryURL() string {
return fmt.Sprintf("https://github.com/%s/%s.git", g.owner, g.project)
}
func (g *GHRepo) Clone(dest string) error {
fullPath := filepath.Join(dest, fmt.Sprintf("%s-%s", g.owner, g.project))
repo, err := git.PlainClone(fullPath, false, &git.CloneOptions{
URL: g.RepositoryURL(),
Progress: os.Stdout,
})
if err != nil {
return err
}
g.repo = repo
g.RepoDir = fullPath
return nil
}
func (g *GHRepo) Checkout(ref string, create bool) error {
opts := &git.CheckoutOptions{
Branch: plumbing.ReferenceName(fmt.Sprintf("refs/heads/%s", ref)),
Create: create,
}
if create {
head, err := g.repo.Head()
if err != nil {
return err
}
opts.Hash = head.Hash()
}
tree, err := g.repo.Worktree()
if err != nil {
return err
}
return tree.Checkout(opts)
}
func (g *GHRepo) AddUpstream(repository *GHRepo) error {
_, err := g.repo.CreateRemote(&config.RemoteConfig{
Name: "upstream",
URLs: []string{repository.RepositoryURL()},
})
return err
}