forked from caarlos0/clone-org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clone-org.go
108 lines (92 loc) · 2.38 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Package cloneorg contains useful functions to find and clone a github
// organization repositories.
package cloneorg
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/google/go-github/v51/github"
"golang.org/x/oauth2"
)
// Repo represents the repository data we need.
type Repo struct {
Name string
URL string
}
// ErrClone happens when a git clone fails.
var ErrClone = errors.New("git clone failed")
// ErrCreateDir happens when we fail to create the target directory.
var ErrCreateDir = errors.New("failed to create directory")
var sem = make(chan bool, 20)
// Clone a given repository into a given destination.
func Clone(repo Repo, destination string) error {
sem <- true
defer func() {
<-sem
}()
// nolint: gosec
cmd := exec.Command(
"git", "clone", "--depth", "1", repo.URL,
filepath.Join(destination, repo.Name),
)
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("%w: %v: %v", ErrClone, repo.Name, string(bts))
}
return nil
}
// AllOrgRepos finds all repositories of a given organization.
func AllOrgRepos(token, org string) (repos []Repo, err error) {
ctx := context.Background()
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
}
const pageSize = 30
func findRepos(ctx context.Context, client *github.Client, org string) (result []*github.Repository, err error) {
opt := &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: pageSize},
}
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
}
// CreateDir creates the directory if it does not exists.
func CreateDir(directory string) error {
stat, err := os.Stat(directory)
directoryDoesNotExists := err != nil
if directoryDoesNotExists {
err := os.MkdirAll(directory, 0o700)
if err != nil {
return fmt.Errorf("%w: %s: %s", ErrCreateDir, directory, err.Error())
}
return nil
}
if stat.IsDir() {
return nil
}
return fmt.Errorf("%w: %s is a file", ErrCreateDir, directory)
}