-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
119 lines (95 loc) · 2.44 KB
/
helpers.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
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"encoding/json"
"fmt"
"os"
"regexp"
"syscall"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4"
"golang.org/x/term"
)
var print = fmt.Println
type Repo struct {
Folder string `json:"folder"`
Url string `json:"url"`
}
// Checks if the URL is a valid git repository via regex (git, ssh, http, https)
func (r *Repo) ValidateUrl() {
gitRepoRegex := regexp.MustCompile(`^((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(\.git)(/)?$`)
isValid := gitRepoRegex.MatchString(r.Url)
if !isValid {
print("Unrecognized git URL:", r.Url)
os.Exit(1)
}
}
type UserParameters struct {
Username, Password, RepoFile string
}
/*
Get username, password
Returning ("", "") means that no authentication will be used to clone the repositories
*/
func getCredentials(username, password string) (string, string) {
empty := ""
userIsProvided := (username != empty)
passwordIsProvided := (password != empty)
if !userIsProvided && !passwordIsProvided {
return empty, empty
}
if userIsProvided && passwordIsProvided {
return username, password
}
if passwordIsProvided && !userIsProvided {
print("If a password is provided, a username must be provided")
os.Exit(1)
}
fmt.Println("Enter password:")
pwd, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
print(err)
os.Exit(1)
}
return username, string(pwd)
}
// Get list of repositories do be cloned
func getRepos(repoFile string) []Repo {
var repos []Repo
content, err := os.Open(repoFile)
if err != nil {
print(err)
os.Exit(1)
}
json.NewDecoder(content).Decode(&repos)
for _, v := range repos {
v.ValidateUrl()
}
return repos
}
func cleanUp(err error, folder string) {
if err != nil {
print(err)
os.Remove(folder)
os.Exit(1)
}
}
/*
Download remote repository:
- username and password are set: clones repo with credentials
- username and password are "": clones repo without credentials
*/
func downloadRepo(repo Repo, username string, password string) {
empty := ""
authRequired := (username != empty) && (password != empty)
if authRequired {
auth := &http.BasicAuth{
Username: username,
Password: password,
}
_, err := git.PlainClone(repo.Folder, false, &git.CloneOptions{URL: repo.Url, Progress: os.Stdout, Auth: auth})
cleanUp(err, repo.Folder)
return
}
_, err := git.PlainClone(repo.Folder, false, &git.CloneOptions{URL: repo.Url, Progress: os.Stdout})
cleanUp(err, repo.Folder)
}