-
Notifications
You must be signed in to change notification settings - Fork 28
/
list_user.go
104 lines (90 loc) · 2.64 KB
/
list_user.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
// SPDX-License-Identifier: Apache-2.0
package repo
import (
"context"
"github.com/go-vela/types/constants"
"github.com/go-vela/types/database"
"github.com/go-vela/types/library"
"github.com/sirupsen/logrus"
)
// ListReposForUser gets a list of repos by user ID from the database.
//
//nolint:lll // ignore long line length due to variable names
func (e *engine) ListReposForUser(ctx context.Context, u *library.User, sortBy string, filters map[string]interface{}, page, perPage int) ([]*library.Repo, int64, error) {
e.logger.WithFields(logrus.Fields{
"user": u.GetName(),
}).Tracef("listing repos for user %s from the database", u.GetName())
// variables to store query results and return values
count := int64(0)
r := new([]database.Repo)
repos := []*library.Repo{}
// count the results
count, err := e.CountReposForUser(ctx, u, filters)
if err != nil {
return repos, 0, err
}
// short-circuit if there are no results
if count == 0 {
return repos, 0, nil
}
// calculate offset for pagination through results
offset := perPage * (page - 1)
switch sortBy {
case "latest":
query := e.client.
Table(constants.TableBuild).
Select("repos.id, MAX(builds.created) AS latest_build").
Joins("INNER JOIN repos repos ON builds.repo_id = repos.id").
Where("repos.user_id = ?", u.GetID()).
Group("repos.id")
err = e.client.
Table(constants.TableRepo).
Select("repos.*").
Joins("LEFT JOIN (?) t on repos.id = t.id", query).
Order("latest_build DESC NULLS LAST").
Limit(perPage).
Offset(offset).
Find(&r).
Error
if err != nil {
return nil, count, err
}
case "name":
fallthrough
default:
err = e.client.
Table(constants.TableRepo).
Where("user_id = ?", u.GetID()).
Where(filters).
Order("name").
Limit(perPage).
Offset(offset).
Find(&r).
Error
if err != nil {
return nil, count, err
}
}
// iterate through all query results
for _, repo := range *r {
// https://golang.org/doc/faq#closures_and_goroutines
tmp := repo
// decrypt the fields for the repo
//
// https://pkg.go.dev/github.com/go-vela/types/database#Repo.Decrypt
err = tmp.Decrypt(e.config.EncryptionKey)
if err != nil {
// TODO: remove backwards compatibility before 1.x.x release
//
// ensures that the change is backwards compatible
// by logging the error instead of returning it
// which allows us to fetch unencrypted repos
e.logger.Errorf("unable to decrypt repo %d: %v", tmp.ID.Int64, err)
}
// convert query result to library type
//
// https://pkg.go.dev/github.com/go-vela/types/database#Repo.ToLibrary
repos = append(repos, tmp.ToLibrary())
}
return repos, count, nil
}