-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgitlab-remote.go
251 lines (207 loc) · 6.72 KB
/
gitlab-remote.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*
Copyright 2018 Wilhelm Peter Püschel
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"log"
"os"
"time"
gitlab "github.com/xanzy/go-gitlab"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
)
// GitlabRemote object
type GitlabRemote struct {
Config *Config
GitlabClient *gitlab.Client
Repo *gitlab.Project
}
// CreateRepo creates a remote repository
func (g *GitlabRemote) CreateRepo() error {
var nsid int
var err error
projectVisibility := gitlab.Visibility(gitlab.InternalVisibility)
if g.Config.private {
projectVisibility = gitlab.Visibility(gitlab.PrivateVisibility)
}
// We need to fetch the namespace id from our group name
nopts := new(gitlab.ListNamespacesOptions)
namepspaces, _, err := g.GitlabClient.Namespaces.ListNamespaces(nopts)
if err != nil {
return err
}
for _, n := range namepspaces {
if n.Name == g.Config.Provider["gitlab"].GroupName {
nsid = n.ID
}
}
if nsid == 0 {
return fmt.Errorf("Could not find namespace id for group %s", g.Config.Provider["gitlab"].GroupName)
}
// We create a new repository
popts := new(gitlab.CreateProjectOptions)
popts.Name = &g.Config.repoName
popts.Visibility = projectVisibility
popts.NamespaceID = &nsid
g.Repo, _, err = g.GitlabClient.Projects.CreateProject(popts)
if err != nil {
log.Fatal(err)
return err
}
// We wait 1 second, just to be sure the repo was created
time.Sleep(time.Second * 1)
// Create a basic README.md
readmecontent := fmt.Sprintf("# %s\n", g.Config.repoName)
commitmsg := "Adding a README\n"
readmepath := fmt.Sprintf("%s/%s", g.Config.Provider["gitlab"].GroupName, g.Config.repoName)
cfopts := new(gitlab.CreateFileOptions)
cfopts.Branch = gitlab.String("master")
cfopts.Content = &readmecontent
cfopts.CommitMessage = &commitmsg
_, _, err = g.GitlabClient.RepositoryFiles.CreateFile(readmepath, "README.md", cfopts)
if err != nil {
return err
}
fmt.Printf("Repository created at %s: %s\n", g.Repo.CreatedAt.Format(time.RFC3339), g.Repo.HTTPURLToRepo)
return nil
}
// CloneRepo clones the remote repository
func (g *GitlabRemote) CloneRepo() error {
fmt.Printf("Cloning %s\n", g.Repo.WebURL)
var err error
var endpoint *transport.Endpoint
// Define a git endpoint
switch g.Config.Provider["gitlab"].CloneProtocol {
case "ssh", "":
endpoint, err = transport.NewEndpoint(g.Repo.SSHURLToRepo)
case "http":
endpoint, err = transport.NewEndpoint(g.Repo.HTTPURLToRepo)
endpoint.User = g.Config.Provider["gitlab"].User
endpoint.Password = g.Config.Provider["gitlab"].Password
default:
err = fmt.Errorf("Unknown clone protocol %s", g.Config.Provider["gitlab"].CloneProtocol)
}
if err != nil {
log.Fatalf("Error creating endpoint: %s\n", err)
return err
}
// Clone the repository
_, err = git.PlainClone(g.Config.localdir, false, &git.CloneOptions{
URL: endpoint.String(),
RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
Progress: os.Stdout,
})
if err != nil {
return err
}
return nil
}
// DeleteRepo deletes a (remote) repository
func (g *GitlabRemote) DeleteRepo() error {
var pid int // Project id
// We need to fetch the project ID for deletion
truep := true
plopts := new(gitlab.ListProjectsOptions)
// Set search options (need to be pointers)
plopts.PerPage = 1000 // We set this to 1000 to get all projects, should suffice
plopts.Owned = &truep // We only want projects we are owner of
projects, _, err := g.GitlabClient.Projects.ListProjects(plopts)
if err != nil {
return err
}
// Check for the right repo and get the id
for _, p := range projects {
if p.PathWithNamespace == fmt.Sprintf("%s/%s", g.Config.Provider["gitlab"].GroupName, g.Config.repoName) {
pid = p.ID
}
}
if pid == 0 {
return fmt.Errorf("Could not find repository %s/%s", g.Config.Provider["gitlab"].GroupName, g.Config.repoName)
}
// Delete the repo
_, err = g.GitlabClient.Projects.DeleteProject(pid)
if err != nil {
return err
}
return nil
}
// ListRepos lists all repos for a given GitlabClient
func (g *GitlabRemote) ListRepos() error {
nsid := 0
truep := true
plopts := new(gitlab.ListProjectsOptions)
// Set search options (need to be pointers)
plopts.PerPage = 1000 // We set this to 1000 to get all projects, should suffice
plopts.Owned = &truep // We only want projects we are owner of
plopts.OrderBy = gitlab.String("last_activity_at")
// We need to fetch the namespace id from our group name
nopts := new(gitlab.ListNamespacesOptions)
namepspaces, _, err := g.GitlabClient.Namespaces.ListNamespaces(nopts)
if err != nil {
return err
}
for _, n := range namepspaces {
if n.Name == g.Config.Provider["gitlab"].GroupName {
nsid = n.ID
}
}
if nsid == 0 {
return fmt.Errorf("Could not find namespace id for group %s", g.Config.Provider["gitlab"].GroupName)
}
// Get a list of projects that we can access
projects, _, err := g.GitlabClient.Projects.ListProjects(plopts)
if err != nil {
return err
}
if g.Config.listLong {
switch g.Config.Provider["gitlab"].CloneProtocol {
case "ssh":
// Loop over projects
for _, p := range projects {
if p.Namespace.ID == nsid {
fmt.Printf("%s - %-36s %s\n", p.LastActivityAt.Format(time.RFC3339), p.Name, p.SSHURLToRepo)
}
}
case "http":
for _, p := range projects {
if p.Namespace.ID == nsid {
fmt.Printf("%s - %-36s %s\n", p.LastActivityAt.Format(time.RFC3339), p.Name, p.HTTPURLToRepo)
}
}
default:
return fmt.Errorf("Unknown cloning protocol: %s", g.Config.Provider["gitlab"].CloneProtocol)
}
} else {
for _, p := range projects {
if p.Namespace.ID == nsid {
fmt.Printf("%s - %s\n", p.LastActivityAt.Format(time.RFC3339), p.Name)
}
}
}
return nil
}
// NewGitlabRemote creates a new Remote object and returns it
func NewGitlabRemote(c *Config) (r *GitlabRemote) {
remote := new(GitlabRemote)
remote.Config = c
remote.GitlabClient = gitlab.NewClient(nil, c.Provider["gitlab"].Token)
remote.GitlabClient.SetBaseURL(c.Provider["gitlab"].HostBaseURL)
remote.Repo = new(gitlab.Project)
// If group name is empty, we set it to user
provider := remote.Config.Provider["gitlab"]
if provider.GroupName == "" {
provider.GroupName = provider.User
remote.Config.Provider["gitlab"] = provider
}
return remote
}