forked from caarlos0/clone-org
/
clone-org.go
69 lines (63 loc) · 1.6 KB
/
clone-org.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
// Package cloneorg contains useful functions to find and clone a github
// organization repositories.
package cloneorg
import (
"context"
"fmt"
"os/exec"
"path/filepath"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
// Repo represents the repository data we need.
type Repo struct {
Name string
URL string
}
// Clone a given repository into a given destination
func Clone(repo Repo, destination string) error {
var cmd = exec.Command(
"git", "clone", "--depth", "1", repo.URL,
filepath.Join(destination, repo.Name),
)
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("git clone failed for %v: %v", repo.Name, string(bts))
}
return nil
}
// AllOrgRepos finds all repositories of a given organization
func AllOrgRepos(token, org string) (repos []Repo, err error) {
var ctx = context.Background()
var client = github.NewClient(oauth2.NewClient(
ctx,
oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),
))
result, err := findRepos(ctx, client, org)
if err != nil {
return
}
for _, repo := range result {
repos = append(repos, Repo{
Name: *repo.Name,
URL: *repo.SSHURL,
})
}
return
}
func findRepos(ctx context.Context, client *github.Client, org string) (result []*github.Repository, err error) {
opt := &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 30},
}
for {
repos, resp, err := client.Repositories.ListByOrg(ctx, org, opt)
if err != nil {
return result, err
}
result = append(result, repos...)
if resp.NextPage == 0 {
break
}
opt.ListOptions.Page = resp.NextPage
}
return result, nil
}