-
Notifications
You must be signed in to change notification settings - Fork 462
/
GitServiceBitbucket.go
226 lines (208 loc) · 9.01 KB
/
GitServiceBitbucket.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
package util
import (
"fmt"
"github.com/ktrysmt/go-bitbucket"
"go.uber.org/zap"
"io/ioutil"
"os"
"path"
"path/filepath"
"time"
)
const (
BITBUCKET_CLONE_BASE_URL = "https://bitbucket.org/"
BITBUCKET_GITOPS_DIR = "bitbucketGitOps"
BITBUCKET_REPO_NOT_FOUND_ERROR = "404 Not Found"
)
type GitBitbucketClient struct {
client *bitbucket.Client
logger *zap.SugaredLogger
gitService GitService
}
func NewGitBitbucketClient(username, token, host string, logger *zap.SugaredLogger, gitService GitService) GitBitbucketClient {
coreClient := bitbucket.NewBasicAuth(username, token)
logger.Infow("bitbucket client created", "clientDetails", coreClient)
return GitBitbucketClient{client: coreClient, logger: logger, gitService: gitService}
}
func (impl GitBitbucketClient) DeleteRepository(name, userName, gitHubOrgName, azureProjectName string, repoOptions *bitbucket.RepositoryOptions) error {
_, err := impl.client.Repositories.Repository.Delete(repoOptions)
if err != nil {
impl.logger.Errorw("error in deleting repo gitlab", "repoName", repoOptions.RepoSlug, "err", err)
}
return err
}
func (impl GitBitbucketClient) GetRepoUrl(repoName string, repoOptions *bitbucket.RepositoryOptions) (repoUrl string, err error) {
_, exists, err := impl.repoExists(repoOptions)
if err != nil {
return "", err
} else if !exists {
return "", fmt.Errorf("%s :repo not found", repoOptions.RepoSlug)
} else {
repoUrl = fmt.Sprintf(BITBUCKET_CLONE_BASE_URL+"%s/%s.git", repoOptions.Owner, repoOptions.RepoSlug)
return repoUrl, nil
}
}
func (impl GitBitbucketClient) CreateRepository(name, description, workSpaceId, projectKey, userName, userEmailId string) (url string, isNew bool, detailedErrorGitOpsConfigActions DetailedErrorGitOpsConfigActions) {
detailedErrorGitOpsConfigActions.StageErrorMap = make(map[string]error)
repoOptions := &bitbucket.RepositoryOptions{
Owner: workSpaceId,
RepoSlug: name,
Scm: "git",
IsPrivate: "true",
Description: description,
Project: projectKey,
}
repoUrl, repoExists, err := impl.repoExists(repoOptions)
if err != nil {
impl.logger.Errorw("error in communication with bitbucket", "err", err)
detailedErrorGitOpsConfigActions.StageErrorMap[GetRepoUrlStage] = err
return "", false, detailedErrorGitOpsConfigActions
}
if repoExists {
detailedErrorGitOpsConfigActions.SuccessfulStages = append(detailedErrorGitOpsConfigActions.SuccessfulStages, GetRepoUrlStage)
return repoUrl, false, detailedErrorGitOpsConfigActions
}
_, err = impl.client.Repositories.Repository.Create(repoOptions)
if err != nil {
impl.logger.Errorw("error in creating repo bitbucket", "project", name, "err", err)
detailedErrorGitOpsConfigActions.StageErrorMap[CreateRepoStage] = err
return "", true, detailedErrorGitOpsConfigActions
}
repoUrl = fmt.Sprintf(BITBUCKET_CLONE_BASE_URL+"%s/%s.git", repoOptions.Owner, repoOptions.RepoSlug)
logger.Infow("repo created ", "repoUrl", repoUrl)
detailedErrorGitOpsConfigActions.SuccessfulStages = append(detailedErrorGitOpsConfigActions.SuccessfulStages, CreateRepoStage)
validated, err := impl.ensureProjectAvailabilityOnHttp(repoOptions)
if err != nil {
impl.logger.Errorw("error in ensuring project availability bitbucket", "repoName", repoOptions.RepoSlug, "err", err)
detailedErrorGitOpsConfigActions.StageErrorMap[CloneHttpStage] = err
return "", true, detailedErrorGitOpsConfigActions
}
if !validated {
detailedErrorGitOpsConfigActions.StageErrorMap[CloneHttpStage] = fmt.Errorf("unable to validate project:%s in given time", name)
return "", true, detailedErrorGitOpsConfigActions
}
detailedErrorGitOpsConfigActions.SuccessfulStages = append(detailedErrorGitOpsConfigActions.SuccessfulStages, CloneHttpStage)
err = impl.createReadme(repoOptions, userName, userEmailId)
if err != nil {
impl.logger.Errorw("error in creating readme bitbucket", "repoName", repoOptions.RepoSlug, "err", err)
detailedErrorGitOpsConfigActions.StageErrorMap[CreateReadmeStage] = err
return "", true, detailedErrorGitOpsConfigActions
}
detailedErrorGitOpsConfigActions.SuccessfulStages = append(detailedErrorGitOpsConfigActions.SuccessfulStages, CreateReadmeStage)
validated, err = impl.ensureProjectAvailabilityOnSsh(repoOptions)
if err != nil {
impl.logger.Errorw("error in ensuring project availability bitbucket", "project", name, "err", err)
detailedErrorGitOpsConfigActions.StageErrorMap[CloneSshStage] = err
return "", true, detailedErrorGitOpsConfigActions
}
if !validated {
detailedErrorGitOpsConfigActions.StageErrorMap[CloneSshStage] = fmt.Errorf("unable to validate project:%s in given time", name)
return "", true, detailedErrorGitOpsConfigActions
}
detailedErrorGitOpsConfigActions.SuccessfulStages = append(detailedErrorGitOpsConfigActions.SuccessfulStages, CloneSshStage)
return repoUrl, true, detailedErrorGitOpsConfigActions
}
func (impl GitBitbucketClient) repoExists(repoOptions *bitbucket.RepositoryOptions) (repoUrl string, exists bool, err error) {
repo, err := impl.client.Repositories.Repository.Get(repoOptions)
if repo == nil && err.Error() == BITBUCKET_REPO_NOT_FOUND_ERROR {
return "", false, nil
}
if err != nil {
return "", false, err
}
repoUrl = fmt.Sprintf(BITBUCKET_CLONE_BASE_URL+"%s/%s.git", repoOptions.Owner, repoOptions.RepoSlug)
return repoUrl, true, nil
}
func (impl GitBitbucketClient) ensureProjectAvailabilityOnHttp(repoOptions *bitbucket.RepositoryOptions) (bool, error) {
for count := 0; count < 5; count++ {
_, exists, err := impl.repoExists(repoOptions)
if err == nil && exists {
impl.logger.Infow("repo validated successfully on https")
return true, nil
} else if err != nil {
impl.logger.Errorw("error in validating repo bitbucket", "repoDetails", repoOptions, "err", err)
return false, err
} else {
impl.logger.Errorw("repo not available on http", "repoDetails", repoOptions)
}
time.Sleep(10 * time.Second)
}
return false, nil
}
func (impl GitBitbucketClient) createReadme(repoOptions *bitbucket.RepositoryOptions, userName, userEmailId string) error {
cfg := &ChartConfig{
ChartName: repoOptions.RepoSlug,
ChartLocation: "",
FileName: "README.md",
FileContent: "@devtron",
ReleaseMessage: "pushing readme",
ChartRepoName: repoOptions.RepoSlug,
UserName: userName,
UserEmailId: userEmailId,
}
_, err := impl.CommitValues(cfg, repoOptions.Owner)
if err != nil {
impl.logger.Errorw("error in creating readme bitbucket", "repo", repoOptions.RepoSlug, "err", err)
}
return err
}
func (impl GitBitbucketClient) ensureProjectAvailabilityOnSsh(repoOptions *bitbucket.RepositoryOptions) (bool, error) {
repoUrl := fmt.Sprintf(BITBUCKET_CLONE_BASE_URL+"%s/%s.git", repoOptions.Owner, repoOptions.RepoSlug)
for count := 0; count < 5; count++ {
_, err := impl.gitService.Clone(repoUrl, fmt.Sprintf("/ensure-clone/%s", repoOptions.RepoSlug))
if err == nil {
impl.logger.Infow("ensureProjectAvailability clone passed bitbucket", "try count", count, "repoUrl", repoUrl)
return true, nil
}
impl.logger.Errorw("ensureProjectAvailability clone failed ssh bitbucket", "try count", count, "err", err)
time.Sleep(10 * time.Second)
}
return false, nil
}
func (impl GitBitbucketClient) CommitValues(config *ChartConfig, bitbucketWorkspaceId string) (commitHash string, err error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
bitbucketGitOpsDirPath := path.Join(homeDir, BITBUCKET_GITOPS_DIR)
if _, err = os.Stat(bitbucketGitOpsDirPath); !os.IsExist(err) {
os.Mkdir(bitbucketGitOpsDirPath, 0777)
}
bitbucketCommitFilePath := path.Join(bitbucketGitOpsDirPath, config.FileName)
if _, err = os.Stat(bitbucketCommitFilePath); os.IsExist(err) {
os.Remove(bitbucketCommitFilePath)
}
err = ioutil.WriteFile(bitbucketCommitFilePath, []byte(config.FileContent), 0666)
if err != nil {
return "", err
}
fileName := filepath.Join(config.ChartLocation, config.FileName)
//bitbucket needs author as - "Name <email-Id>"
authorBitbucket := fmt.Sprintf("%s <%s>", config.UserName, config.UserEmailId)
repoWriteOptions := &bitbucket.RepositoryBlobWriteOptions{
Owner: bitbucketWorkspaceId,
RepoSlug: config.ChartRepoName,
FilePath: bitbucketCommitFilePath,
FileName: fileName,
Message: config.ReleaseMessage,
Branch: "master",
Author: authorBitbucket,
}
err = impl.client.Repositories.Repository.WriteFileBlob(repoWriteOptions)
_ = os.Remove(bitbucketCommitFilePath)
if err != nil {
return "", err
}
commitOptions := &bitbucket.CommitsOptions{
RepoSlug: config.ChartRepoName,
Owner: bitbucketWorkspaceId,
Branchortag: "master",
}
commits, err := impl.client.Repositories.Commits.GetCommits(commitOptions)
if err != nil {
return "", err
}
//extracting the latest commit hash from the paginated api response of above method, reference of api & response - https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/commits
commitHash = commits.(map[string]interface{})["values"].([]interface{})[0].(map[string]interface{})["hash"].(string)
return commitHash, nil
}