This repository was archived by the owner on Mar 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathgitContents.go
766 lines (661 loc) · 24.4 KB
/
gitContents.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
package server
import (
"bytes"
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/gimlet-io/gimlet/cmd/dashboard/config"
"github.com/gimlet-io/gimlet/cmd/dashboard/dynamicconfig"
"github.com/gimlet-io/gimlet/pkg/dashboard/api"
"github.com/gimlet-io/gimlet/pkg/dashboard/model"
"github.com/gimlet-io/gimlet/pkg/dashboard/store"
"github.com/gimlet-io/gimlet/pkg/dx"
"github.com/gimlet-io/gimlet/pkg/git/customScm"
"github.com/gimlet-io/gimlet/pkg/git/genericScm"
"github.com/gimlet-io/gimlet/pkg/git/nativeGit"
helper "github.com/gimlet-io/gimlet/pkg/git/nativeGit"
"github.com/gimlet-io/go-scm/scm"
"github.com/go-chi/chi/v5"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/storer"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
func branches(w http.ResponseWriter, r *http.Request) {
owner := chi.URLParam(r, "owner")
name := chi.URLParam(r, "name")
repoName := fmt.Sprintf("%s/%s", owner, name)
ctx := r.Context()
gitRepoCache, _ := ctx.Value("gitRepoCache").(*nativeGit.RepoCache)
var refIter storer.ReferenceIter
var innerErr error
branches := []string{}
err := gitRepoCache.PerformAction(repoName, func(repo *git.Repository) error {
refIter, innerErr = repo.References()
return innerErr
})
if err != nil {
logrus.Errorf("cannot get refs: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
refIter.ForEach(func(r *plumbing.Reference) error {
if r.Name().IsRemote() {
branch := r.Name().Short()
branches = append(branches, strings.TrimPrefix(branch, "origin/"))
}
return nil
})
branchesString, err := json.Marshal(branches)
if err != nil {
logrus.Errorf("cannot serialize branches: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(branchesString)
}
func getMetas(w http.ResponseWriter, r *http.Request) {
owner := chi.URLParam(r, "owner")
repo := chi.URLParam(r, "name")
ctx := r.Context()
gitRepoCache, _ := ctx.Value("gitRepoCache").(*nativeGit.RepoCache)
repoName := fmt.Sprintf("%s/%s", owner, repo)
var err error
var headBranch string
var files map[string]string
err = gitRepoCache.PerformAction(repoName, func(repo *git.Repository) error {
var innerErr error
headBranch, innerErr = nativeGit.HeadBranch(repo)
if innerErr != nil {
return innerErr
}
files, innerErr = helper.RemoteFolderOnBranchWithoutCheckout(repo, "", ".gimlet")
return innerErr
})
if err != nil {
if !strings.Contains(err.Error(), "directory not found") {
logrus.Errorf("cannot list files in .gimlet/: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
fileInfos := []fileInfo{}
for fileName, content := range files {
var envConfig dx.Manifest
err = yaml.Unmarshal([]byte(content), &envConfig)
if err != nil {
logrus.Warnf("cannot parse env config string: %s", err)
continue
}
fileInfos = append(fileInfos, fileInfo{
AppName: envConfig.App,
EnvName: envConfig.Env,
FileName: fileName,
Branch: headBranch,
})
}
gitRepoM := gitRepoMetas{
FileInfos: fileInfos,
}
gitRepoMString, err := json.Marshal(gitRepoM)
if err != nil {
logrus.Errorf("cannot serialize repo meta: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(gitRepoMString)
}
func configChangePullRequestsPerConfig(w http.ResponseWriter, r *http.Request) {
owner := chi.URLParam(r, "owner")
repoName := chi.URLParam(r, "name")
env := chi.URLParam(r, "env")
config := chi.URLParam(r, "config")
repoPath := fmt.Sprintf("%s/%s", owner, repoName)
ctx := r.Context()
dynamicConfig := ctx.Value("dynamicConfig").(*dynamicconfig.DynamicConfig)
goScm := genericScm.NewGoScmHelper(dynamicConfig, nil)
tokenManager := ctx.Value("tokenManager").(customScm.NonImpersonatedTokenManager)
token, _, _ := tokenManager.Token()
prList, err := goScm.ListOpenPRs(token, repoPath)
if err != nil {
logrus.Errorf("cannot list pull requests: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
pullRequestsPerEnvConfig := []*api.PR{}
for _, pullRequest := range prList {
if !strings.HasPrefix(pullRequest.Source, "gimlet-config-change") {
continue
}
if !strings.Contains(pullRequest.Source, env) {
continue
}
if !strings.Contains(pullRequest.Title, fmt.Sprintf("`%s`", config)) {
continue
}
pullRequestsPerEnvConfig = append(pullRequestsPerEnvConfig, &api.PR{
Branch: pullRequest.Source,
Sha: pullRequest.Sha,
Link: pullRequest.Link,
Title: pullRequest.Title,
Number: pullRequest.Number,
Author: pullRequest.Author.Login,
Created: int(pullRequest.Created.Unix()),
Updated: int(pullRequest.Updated.Unix()),
})
}
pullRequestsString, err := json.Marshal(pullRequestsPerEnvConfig)
if err != nil {
logrus.Errorf("cannot serialize pull requests: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(pullRequestsString)
}
func getPullRequests(w http.ResponseWriter, r *http.Request) {
owner := chi.URLParam(r, "owner")
repoName := chi.URLParam(r, "name")
repoPath := fmt.Sprintf("%s/%s", owner, repoName)
ctx := r.Context()
dynamicConfig := ctx.Value("dynamicConfig").(*dynamicconfig.DynamicConfig)
goScm := genericScm.NewGoScmHelper(dynamicConfig, nil)
tokenManager := ctx.Value("tokenManager").(customScm.NonImpersonatedTokenManager)
token, _, _ := tokenManager.Token()
prList, err := goScm.ListOpenPRs(token, repoPath)
if err != nil {
logrus.Errorf("cannot list pull requests: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
pullRequests := []*api.PR{}
for _, pullRequest := range prList {
pullRequests = append(pullRequests, &api.PR{
Branch: pullRequest.Source,
Sha: pullRequest.Sha,
Link: pullRequest.Link,
Title: pullRequest.Title,
Number: pullRequest.Number,
Author: pullRequest.Author.Login,
Created: int(pullRequest.Created.Unix()),
Updated: int(pullRequest.Updated.Unix()),
})
}
pullRequestsString, err := json.Marshal(pullRequests)
if err != nil {
logrus.Errorf("cannot serialize pull requests: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(pullRequestsString)
}
func getChartUpdatePullRequests(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
chartUpdatePullRequests := ctx.Value("chartUpdatePullRequests").(*map[string]interface{})
pullRequestsString, err := json.Marshal(chartUpdatePullRequests)
if err != nil {
logrus.Errorf("cannot serialize pull requests: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(pullRequestsString)
}
func getGitopsUpdatePullRequests(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
env := chi.URLParam(r, "env")
gitopsUpdatePullRequests := ctx.Value("gitopsUpdatePullRequests").(*map[string]interface{})
gitopsUpdatePullRequestsPerEnv := []*api.PR{}
if (*gitopsUpdatePullRequests)[env] != nil {
gitopsUpdatePullRequestsPerEnv = (*gitopsUpdatePullRequests)[env].([]*api.PR)
}
gitopsUpdatePullRequestsString, err := json.Marshal(gitopsUpdatePullRequestsPerEnv)
if err != nil {
logrus.Errorf("cannot serialize pull requests: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(gitopsUpdatePullRequestsString)
}
func getPullRequestsFromInfraRepos(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
envParam := r.URL.Query().Get("env")
dynamicConfig := ctx.Value("dynamicConfig").(*dynamicconfig.DynamicConfig)
goScm := genericScm.NewGoScmHelper(dynamicConfig, nil)
tokenManager := ctx.Value("tokenManager").(customScm.NonImpersonatedTokenManager)
token, _, _ := tokenManager.Token()
db := r.Context().Value("store").(*store.Store)
envsFromDB, err := db.GetEnvironments()
if err != nil {
logrus.Errorf("cannot get all environments from database: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
prListCreatedByGimlet := []*api.PR{}
for _, env := range envsFromDB {
owner, _ := scm.Split(env.InfraRepo)
if owner == "builtin" || env.Name != envParam {
continue
}
prList, err := goScm.ListOpenPRs(token, env.InfraRepo)
if err != nil {
if !strings.Contains(err.Error(), "Not Found") {
logrus.Errorf("cannot list pull requests: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
for _, pullRequest := range prList {
if strings.HasPrefix(pullRequest.Source, "gimlet-stack") && strings.Contains(pullRequest.Source, env.Name) {
prListCreatedByGimlet = append(prListCreatedByGimlet, &api.PR{
Sha: pullRequest.Sha,
Link: pullRequest.Link,
Title: pullRequest.Title,
Branch: pullRequest.Source,
Number: pullRequest.Number,
Author: pullRequest.Author.Login,
Created: int(pullRequest.Created.Unix()),
Updated: int(pullRequest.Updated.Unix()),
})
}
}
}
PullRequestsString, err := json.Marshal(prListCreatedByGimlet)
if err != nil {
logrus.Errorf("cannot serialize pull requests: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(PullRequestsString)
}
type fileInfo struct {
EnvName string `json:"envName"`
AppName string `json:"appName"`
FileName string `json:"fileName"`
Branch string `json:"branch"`
}
type gitRepoMetas struct {
FileInfos []fileInfo `json:"fileInfos"`
PullRequestPolicy bool `json:"pullRequestPolicy"`
}
// envConfig fetches all environment configs from source control for a repo
func envConfigs(w http.ResponseWriter, r *http.Request) {
owner := chi.URLParam(r, "owner")
repo := chi.URLParam(r, "name")
ctx := r.Context()
gitRepoCache, _ := ctx.Value("gitRepoCache").(*nativeGit.RepoCache)
repoName := fmt.Sprintf("%s/%s", owner, repo)
var files map[string]string
var err error
err = gitRepoCache.PerformAction(repoName, func(repo *git.Repository) error {
var innerErr error
files, innerErr = helper.RemoteFolderOnBranchWithoutCheckout(repo, "", ".gimlet")
return innerErr
})
if err != nil {
if strings.Contains(err.Error(), "directory not found") {
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
return
} else {
logrus.Errorf("cannot list files in .gimlet/: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
envConfigs := []dx.Manifest{}
for _, content := range files {
var envConfig dx.Manifest
err = yaml.Unmarshal([]byte(content), &envConfig)
if err != nil {
logrus.Warnf("cannot parse env config string: %s", err)
continue
}
envConfigs = append(envConfigs, envConfig)
}
configsPerEnv := map[string][]dx.Manifest{}
for _, config := range envConfigs {
if configsPerEnv[config.Env] == nil {
configsPerEnv[config.Env] = []dx.Manifest{}
}
configsPerEnv[config.Env] = append(configsPerEnv[config.Env], config)
}
configsPerEnvJson, err := json.Marshal(configsPerEnv)
if err != nil {
logrus.Errorf("cannot convert envconfigs to json: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(configsPerEnvJson))
}
type DeploymentTemplate struct {
Reference config.DefaultChart `json:"reference"`
Schema interface{} `json:"schema"`
UISchema interface{} `json:"uiSchema"`
}
func saveEnvConfig(w http.ResponseWriter, r *http.Request) {
var envConfigData dx.Manifest
err := json.NewDecoder(r.Body).Decode(&envConfigData)
if err != nil {
logrus.Errorf("cannot decode env config data: %s", err)
http.Error(w, http.StatusText(400), 400)
return
}
owner := chi.URLParam(r, "owner")
repoName := chi.URLParam(r, "name")
repoPath := fmt.Sprintf("%s/%s", owner, repoName)
env := envConfigData.Env
ctx := r.Context()
gitRepoCache, _ := ctx.Value("gitRepoCache").(*nativeGit.RepoCache)
tokenManager := ctx.Value("tokenManager").(customScm.NonImpersonatedTokenManager)
token, _, _ := tokenManager.Token()
dynamicConfig := ctx.Value("dynamicConfig").(*dynamicconfig.DynamicConfig)
user := ctx.Value("user").(*model.User)
goScm := genericScm.NewGoScmHelper(dynamicConfig, nil)
repo, tmpPath, err := gitRepoCache.InstanceForWrite(fmt.Sprintf("%s/%s", owner, repoName))
defer os.RemoveAll(tmpPath)
if err != nil {
logrus.Errorf("cannot get repo: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
headBranch, err := helper.HeadBranch(repo)
if err != nil {
logrus.Errorf("cannot get head branch: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
existingEnvConfigs, err := existingEnvConfigs(repo, headBranch)
if err != nil {
logrus.Errorf(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
envConfigFileName := envConfigPath(env, envConfigData.App, existingEnvConfigs)
envConfigFilePath := fmt.Sprintf(".gimlet/%s", envConfigFileName)
createCase := false // indicates if we need to create the file, we update existing manifests on the default path
_, _, err = goScm.Content(token, repoPath, url.QueryEscape(envConfigFilePath), headBranch)
if err != nil {
if strings.Contains(err.Error(), "Not Found") {
createCase = true
} else {
logrus.Errorf("cannot fetch envConfig from github: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
w.Write([]byte("{}"))
return
}
}
if !createCase && existingEnvConfigs[envConfigFileName].App != envConfigData.App { // we do not allow updating application names
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
// marshall and ident the manifest
var toSaveBuffer bytes.Buffer
yamlEncoder := yaml.NewEncoder(&toSaveBuffer)
yamlEncoder.SetIndent(2)
err = yamlEncoder.Encode(&envConfigData)
if err != nil {
logrus.Errorf("cannot marshal manifest: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
dao := ctx.Value("store").(*store.Store)
pullRequestPolicy, err := dao.RepoHasPullRequestPolicy(repoPath)
if err != nil {
logrus.Errorf("cannot get pull request policy for %s: %s", repoPath, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var sourceBranch string
if pullRequestPolicy {
// generate branch name to write changes on
sourceBranch, err = GenerateBranchNameWithUniqueHash(fmt.Sprintf("gimlet-config-change-%s", env), 4)
if err != nil {
logrus.Errorf("cannot generate branch name: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
err = helper.Branch(repo, fmt.Sprintf("refs/heads/%s", sourceBranch))
if err != nil {
logrus.Errorf("cannot checkout branch: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
message := fmt.Sprintf("[Gimlet] Updating %s gimlet manifest for the %s env", envConfigData.App, env)
if createCase {
message = fmt.Sprintf("[Gimlet] Creating %s gimlet manifest for the %s env", envConfigData.App, env)
}
_ = os.MkdirAll(filepath.Join(tmpPath, ".gimlet"), nativeGit.Dir_RWX_RX_R)
err = os.WriteFile(filepath.Join(tmpPath, envConfigFilePath), toSaveBuffer.Bytes(), nativeGit.Dir_RWX_RX_R)
if err != nil {
logrus.Errorf("cannot write file: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
hash, err := stageCommitAndPushWithHash(repo, tmpPath, token, message)
if err != nil {
logrus.Errorf("cannot stage commit and push: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if !pullRequestPolicy {
response := map[string]interface{}{
"link": fmt.Sprintf("%s/%s/commit/%s", dynamicConfig.ScmURL(), repoPath, hash),
}
responseJson, err := json.Marshal(response)
if err != nil {
logrus.Errorf("cannot marshal response: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
gitRepoCache.Invalidate(repoPath)
w.WriteHeader(http.StatusOK)
w.Write(responseJson)
return
}
createdPR, _, err := goScm.CreatePR(token, repoPath, sourceBranch, headBranch,
fmt.Sprintf("[Gimlet] `%s` ➡️ `%s` deployment configuration change", envConfigData.App, env),
fmt.Sprintf("@%s is editing the `%s` deployment configuration for the `%s` environment.", user.Login, envConfigData.App, env))
if err != nil {
logrus.Errorf("cannot create pr: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
response := map[string]interface{}{
"link": createdPR.Link,
}
responseJson, err := json.Marshal(response)
if err != nil {
logrus.Errorf("cannot marshal response: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
gitRepoCache.Invalidate(repoPath)
w.WriteHeader(http.StatusOK)
w.Write(responseJson)
}
func deleteEnvConfig(w http.ResponseWriter, r *http.Request) {
owner := chi.URLParam(r, "owner")
repoName := chi.URLParam(r, "name")
repoPath := fmt.Sprintf("%s/%s", owner, repoName)
env := chi.URLParam(r, "env")
configName := chi.URLParam(r, "config")
ctx := r.Context()
gitRepoCache, _ := ctx.Value("gitRepoCache").(*nativeGit.RepoCache)
tokenManager := ctx.Value("tokenManager").(customScm.NonImpersonatedTokenManager)
token, _, _ := tokenManager.Token()
dynamicConfig := ctx.Value("dynamicConfig").(*dynamicconfig.DynamicConfig)
user := ctx.Value("user").(*model.User)
goScm := genericScm.NewGoScmHelper(dynamicConfig, nil)
repo, tmpPath, err := gitRepoCache.InstanceForWrite(fmt.Sprintf("%s/%s", owner, repoName))
defer os.RemoveAll(tmpPath)
if err != nil {
logrus.Errorf("cannot get repo: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
headBranch, err := helper.HeadBranch(repo)
if err != nil {
logrus.Errorf("cannot get head branch: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
existingEnvConfigs, err := existingEnvConfigs(repo, headBranch)
if err != nil {
logrus.Errorf(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
envConfigFileName := envConfigPath(env, configName, existingEnvConfigs)
envConfigFilePath := fmt.Sprintf(".gimlet/%s", envConfigFileName)
_, _, err = goScm.Content(token, repoPath, envConfigFilePath, headBranch)
if err != nil {
if strings.Contains(err.Error(), "Not Found") {
logrus.Errorf("config file not found: %s", err)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
w.Write([]byte("{}"))
return
} else {
logrus.Errorf("cannot fetch envConfig from github: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
w.Write([]byte("{}"))
return
}
}
dao := ctx.Value("store").(*store.Store)
pullRequestPolicy, err := dao.RepoHasPullRequestPolicy(repoPath)
if err != nil {
logrus.Errorf("cannot get pull request policy for %s: %s", repoPath, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var sourceBranch string
if pullRequestPolicy {
sourceBranch, err = GenerateBranchNameWithUniqueHash(fmt.Sprintf("gimlet-config-change-%s", env), 4)
if err != nil {
logrus.Errorf("cannot generate branch name: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
err = helper.Branch(repo, fmt.Sprintf("refs/heads/%s", sourceBranch))
if err != nil {
logrus.Errorf("cannot checkout branch: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
err = os.Remove(filepath.Join(tmpPath, envConfigFilePath))
if err != nil {
logrus.Errorf("cannot write file: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
hash, err := stageCommitAndPushWithHash(repo, tmpPath, token, fmt.Sprintf("[Gimlet] Deleting %s gimlet manifest for the %s env", configName, env))
if err != nil {
logrus.Errorf("cannot stage commit and push: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if !pullRequestPolicy {
response := map[string]interface{}{
"link": fmt.Sprintf("%s/%s/commit/%s", dynamicConfig.ScmURL(), repoPath, hash),
}
responseJson, err := json.Marshal(response)
if err != nil {
logrus.Errorf("cannot marshal response: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(responseJson)
return
}
createdPR, _, err := goScm.CreatePR(token, repoPath, sourceBranch, headBranch,
fmt.Sprintf("[Gimlet] `%s` ➡️ `%s` deployment configuration change", configName, env),
fmt.Sprintf("@%s is deleting the `%s` deployment configuration for the `%s` environment.", user.Login, configName, env))
if err != nil {
logrus.Errorf("cannot create pr: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
response := map[string]interface{}{
"link": createdPR.Link,
}
responseJson, err := json.Marshal(response)
if err != nil {
logrus.Errorf("cannot marshal manifest: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
gitRepoCache.Invalidate(repoPath)
w.WriteHeader(http.StatusOK)
w.Write(responseJson)
}
// envConfigPath returns the envconfig file name based on convention, or the name of an existing file describing this env
func envConfigPath(env string, appName string, existingEnvConfigs map[string]*dx.Manifest) string {
envConfigFileName := fmt.Sprintf("%s-%s.yaml", env, appName)
for fileName, existingEnvConfig := range existingEnvConfigs {
if existingEnvConfig.Env == env &&
existingEnvConfig.App == appName {
envConfigFileName = fileName
break
}
}
return envConfigFileName
}
func existingEnvConfigs(repo *git.Repository, headBranch string) (map[string]*dx.Manifest, error) {
files, err := helper.RemoteFolderOnBranchWithoutCheckout(repo, headBranch, ".gimlet")
if err != nil {
if !strings.Contains(err.Error(), "directory not found") {
return nil, fmt.Errorf("cannot list files in .gimlet/: %s", err)
}
}
existingEnvConfigs := map[string]*dx.Manifest{}
for fileName, content := range files {
var envConfig dx.Manifest
err = yaml.Unmarshal([]byte(content), &envConfig)
if err != nil {
logrus.Warnf("cannot parse env config string: %s", err)
continue
}
existingEnvConfigs[fileName] = &envConfig
}
return existingEnvConfigs, nil
}
func getImportedRepos(dao *store.Store) ([]string, error) {
var importedRepos []string
importedReposJson, err := dao.KeyValue(model.ImportedRepos)
if err != nil && err != sql.ErrNoRows {
return nil, err
}
if importedReposJson.Value == "" {
importedReposJson.Value = "[]"
}
err = json.Unmarshal([]byte(importedReposJson.Value), &importedRepos)
if err != nil {
return nil, err
}
return importedRepos, nil
}
func GenerateBranchNameWithUniqueHash(defaultBranchName string, uniqieHashlength int) (string, error) {
b := make([]byte, uniqieHashlength)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return fmt.Sprintf("%s-%s", defaultBranchName, hex.EncodeToString(b)), nil
}