Browse Source

[Vendor] Update xanzy/go-gitlab v0.31.0 => v0.37.0 (#12701)

* update github.com/xanzy/go-gitlab v0.31.0 => v0.37.0

* vendor

* adapt changes

Co-authored-by: techknowlogick <techknowlogick@gitea.io>
mj-v1.14.3
6543 2 years ago
committed by GitHub
parent
commit
0c6a802731
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      go.mod
  2. 21
      go.sum
  3. 4
      modules/migrations/gitlab.go
  4. 12
      vendor/github.com/hashicorp/go-retryablehttp/.travis.yml
  5. 173
      vendor/github.com/hashicorp/go-retryablehttp/client.go
  6. 11
      vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go
  7. 3
      vendor/github.com/xanzy/go-gitlab/README.md
  8. 2
      vendor/github.com/xanzy/go-gitlab/branches.go
  9. 10
      vendor/github.com/xanzy/go-gitlab/client_options.go
  10. 13
      vendor/github.com/xanzy/go-gitlab/commits.go
  11. 1
      vendor/github.com/xanzy/go-gitlab/deployments.go
  12. 133
      vendor/github.com/xanzy/go-gitlab/epic_issues.go
  13. 63
      vendor/github.com/xanzy/go-gitlab/epics.go
  14. 9
      vendor/github.com/xanzy/go-gitlab/event_webhook_types.go
  15. 496
      vendor/github.com/xanzy/go-gitlab/gitlab.go
  16. 18
      vendor/github.com/xanzy/go-gitlab/group_clusters.go
  17. 29
      vendor/github.com/xanzy/go-gitlab/group_labels.go
  18. 44
      vendor/github.com/xanzy/go-gitlab/group_members.go
  19. 39
      vendor/github.com/xanzy/go-gitlab/group_milestones.go
  20. 76
      vendor/github.com/xanzy/go-gitlab/groups.go
  21. 151
      vendor/github.com/xanzy/go-gitlab/instance_clusters.go
  22. 179
      vendor/github.com/xanzy/go-gitlab/instance_variables.go
  23. 220
      vendor/github.com/xanzy/go-gitlab/issues.go
  24. 186
      vendor/github.com/xanzy/go-gitlab/issues_statistics.go
  25. 57
      vendor/github.com/xanzy/go-gitlab/labels.go
  26. 29
      vendor/github.com/xanzy/go-gitlab/license.go
  27. 52
      vendor/github.com/xanzy/go-gitlab/merge_requests.go
  28. 1
      vendor/github.com/xanzy/go-gitlab/milestones.go
  29. 19
      vendor/github.com/xanzy/go-gitlab/pipeline_schedules.go
  30. 2
      vendor/github.com/xanzy/go-gitlab/pipelines.go
  31. 145
      vendor/github.com/xanzy/go-gitlab/project_mirror.go
  32. 4
      vendor/github.com/xanzy/go-gitlab/project_snippets.go
  33. 300
      vendor/github.com/xanzy/go-gitlab/projects.go
  34. 25
      vendor/github.com/xanzy/go-gitlab/protected_branches.go
  35. 97
      vendor/github.com/xanzy/go-gitlab/repository_files.go
  36. 38
      vendor/github.com/xanzy/go-gitlab/runners.go
  37. 52
      vendor/github.com/xanzy/go-gitlab/services.go
  38. 1
      vendor/github.com/xanzy/go-gitlab/tags.go
  39. 430
      vendor/github.com/xanzy/go-gitlab/types.go
  40. 2
      vendor/github.com/xanzy/go-gitlab/users.go
  41. 10
      vendor/golang.org/x/time/rate/rate.go
  42. 6
      vendor/golang.org/x/tools/internal/analysisinternal/analysis.go
  43. 33
      vendor/golang.org/x/tools/internal/imports/fix.go
  44. 8
      vendor/modules.txt

8
go.mod

@ -50,7 +50,7 @@ require (
github.com/google/go-github/v32 v32.1.0
github.com/google/uuid v1.1.1
github.com/gorilla/context v1.1.1
github.com/hashicorp/go-retryablehttp v0.6.6 // indirect
github.com/hashicorp/go-retryablehttp v0.6.7 // indirect
github.com/hashicorp/go-version v0.0.0-00010101000000-000000000000
github.com/huandu/xstrings v1.3.0
github.com/issue9/assert v1.3.2 // indirect
@ -94,7 +94,7 @@ require (
github.com/unknwon/i18n v0.0.0-20190805065654-5c6446a380b6
github.com/unknwon/paginater v0.0.0-20151104151617-7748a72e0141
github.com/urfave/cli v1.20.0
github.com/xanzy/go-gitlab v0.31.0
github.com/xanzy/go-gitlab v0.37.0
github.com/yohcop/openid-go v1.0.0
github.com/yuin/goldmark v1.2.1
github.com/yuin/goldmark-highlighting v0.0.0-20200307114337-60d527fdb691
@ -104,8 +104,8 @@ require (
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae
golang.org/x/text v0.3.3
golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1 // indirect
golang.org/x/tools v0.0.0-20200814230902-9882f1d1823d
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e // indirect
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/asn1-ber.v1 v1.0.0-20150924051756-4e86f4367175 // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df

21
go.sum

@ -477,8 +477,8 @@ github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjh
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-retryablehttp v0.6.4/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY=
github.com/hashicorp/go-retryablehttp v0.6.6 h1:HJunrbHTDDbBb/ay4kxa1n+dLmttUlnP3V9oNE4hmsM=
github.com/hashicorp/go-retryablehttp v0.6.6/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY=
github.com/hashicorp/go-retryablehttp v0.6.7 h1:8/CAEZt/+F7kR7GevNHulKkUjLht3CPmn7egmhieNKo=
github.com/hashicorp/go-retryablehttp v0.6.7/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY=
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
@ -888,8 +888,8 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
github.com/willf/bitset v1.1.10 h1:NotGKqX0KwQ72NUzqrjZq5ipPNDQex9lo3WpaS8L2sc=
github.com/willf/bitset v1.1.10/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4=
github.com/xanzy/go-gitlab v0.31.0 h1:+nHztQuCXGSMluKe5Q9IRaPdz6tO8O0gMkQ0vqGpiBk=
github.com/xanzy/go-gitlab v0.31.0/go.mod h1:sPLojNBn68fMUWSxIJtdVVIP8uSBYqesTfDUseX11Ug=
github.com/xanzy/go-gitlab v0.37.0 h1:Z/CQkjj5VwbWVYVL7S70kS/TFj5H/pJumV7xbJ0YUQ8=
github.com/xanzy/go-gitlab v0.37.0/go.mod h1:sPLojNBn68fMUWSxIJtdVVIP8uSBYqesTfDUseX11Ug=
github.com/xanzy/ssh-agent v0.2.1 h1:TCbipTQL2JiiCprBWx9frJ2eJlCYT00NmctrHxVAr70=
github.com/xanzy/ssh-agent v0.2.1/go.mod h1:mLlQY/MoOhWBj+gOGMQkOeiEvkx+8pJSI+0Bx9h2kr4=
github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I=
@ -1072,15 +1072,14 @@ golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae h1:Ih9Yo4hSPImZOpfGuA4bR/ORK
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1 h1:NusfzzA6yGQ+ua51ck7E3omNUX/JuqbFSaRGqU8CcLI=
golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e h1:EHBhcS0mlXEAVwNyO2dLfjToGsyY4j24pTs2ScHnX7s=
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@ -1111,11 +1110,10 @@ golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtn
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200225230052-807dcd883420/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200325010219-a49f79bcc224 h1:azwY/v0y0K4mFHVsg5+UrTgchqALYWpqVo6vL5OmkmI=
golang.org/x/tools v0.0.0-20200325010219-a49f79bcc224/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200814230902-9882f1d1823d h1:XZxUC4/ZNKTjrT4/Oc9gCgIYnzPW3/CefdPjsndrVWM=
golang.org/x/tools v0.0.0-20200814230902-9882f1d1823d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d h1:W07d4xkoAUSNOkOzdzXCdFGxT7o2rW4q8M34tB2i//k=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@ -1160,7 +1158,6 @@ google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0 h1:cJv5/xdbk1NnMPR1VP9+HU6gupuG9MLBoH1r6RHZ2MY=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
@ -1187,9 +1184,7 @@ gopkg.in/ini.v1 v1.44.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.44.2/go.mod h1:M3Cogqpuv0QCi3ExAY5V4uOt4qb/R3xZubo9m8lK5wg=
gopkg.in/ini.v1 v1.46.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.57.0 h1:9unxIsFcTt4I55uWluz+UmL95q4kdJ0buvQ1ZIqVQww=
gopkg.in/ini.v1 v1.57.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.60.1 h1:P5y5shSkb0CFe44qEeMBgn8JLow09MP17jlJHanke5g=
gopkg.in/ini.v1 v1.60.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.60.2 h1:7i8mqModL63zqi8nQn8Q3+0zvSCZy1AxhBgthKfi4WU=
gopkg.in/ini.v1 v1.60.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=

4
modules/migrations/gitlab.go

@ -234,10 +234,10 @@ func (g *GitlabDownloader) GetLabels() ([]*base.Label, error) {
var perPage = 100
var labels = make([]*base.Label, 0, perPage)
for i := 1; ; i++ {
ls, _, err := g.client.Labels.ListLabels(g.repoID, &gitlab.ListLabelsOptions{
ls, _, err := g.client.Labels.ListLabels(g.repoID, &gitlab.ListLabelsOptions{ListOptions: gitlab.ListOptions{
Page: i,
PerPage: perPage,
}, nil, gitlab.WithContext(g.ctx))
}}, nil, gitlab.WithContext(g.ctx))
if err != nil {
return nil, err
}

12
vendor/github.com/hashicorp/go-retryablehttp/.travis.yml

@ -1,12 +0,0 @@
sudo: false
language: go
go:
- 1.12.4
branches:
only:
- master
script: make updatedeps test

173
vendor/github.com/hashicorp/go-retryablehttp/client.go

@ -35,11 +35,12 @@ import (
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/hashicorp/go-cleanhttp"
cleanhttp "github.com/hashicorp/go-cleanhttp"
)
var (
@ -276,12 +277,16 @@ type Logger interface {
Printf(string, ...interface{})
}
// LeveledLogger interface implements the basic methods that a logger library needs
// LeveledLogger is an interface that can be implemented by any logger or a
// logger wrapper to provide leveled logging. The methods accept a message
// string and a variadic number of key-value pairs. For log.Printf style
// formatting where message string contains a format specifier, use Logger
// interface.
type LeveledLogger interface {
Error(string, ...interface{})
Info(string, ...interface{})
Debug(string, ...interface{})
Warn(string, ...interface{})
Error(msg string, keysAndValues ...interface{})
Info(msg string, keysAndValues ...interface{})
Debug(msg string, keysAndValues ...interface{})
Warn(msg string, keysAndValues ...interface{})
}
// hookLogger adapts an LeveledLogger to Logger for use by the existing hook functions
@ -357,6 +362,7 @@ type Client struct {
ErrorHandler ErrorHandler
loggerInit sync.Once
clientInit sync.Once
}
// NewClient creates a new Client with default settings.
@ -420,6 +426,13 @@ func DefaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bo
return true, nil
}
// 429 Too Many Requests is recoverable. Sometimes the server puts
// a Retry-After response header to indicate when the server is
// available to start processing request from client.
if resp.StatusCode == http.StatusTooManyRequests {
return true, nil
}
// Check the response code. We retry on 500-range responses to allow
// the server time to recover, as 500's are typically not permanent
// errors and may relate to outages on the server side. This will catch
@ -431,10 +444,66 @@ func DefaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bo
return false, nil
}
// ErrorPropagatedRetryPolicy is the same as DefaultRetryPolicy, except it
// propagates errors back instead of returning nil. This allows you to inspect
// why it decided to retry or not.
func ErrorPropagatedRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) {
// do not retry on context.Canceled or context.DeadlineExceeded
if ctx.Err() != nil {
return false, ctx.Err()
}
if err != nil {
if v, ok := err.(*url.Error); ok {
// Don't retry if the error was due to too many redirects.
if redirectsErrorRe.MatchString(v.Error()) {
return false, v
}
// Don't retry if the error was due to an invalid protocol scheme.
if schemeErrorRe.MatchString(v.Error()) {
return false, v
}
// Don't retry if the error was due to TLS cert verification failure.
if _, ok := v.Err.(x509.UnknownAuthorityError); ok {
return false, v
}
}
// The error is likely recoverable so retry.
return true, nil
}
// Check the response code. We retry on 500-range responses to allow
// the server time to recover, as 500's are typically not permanent
// errors and may relate to outages on the server side. This will catch
// invalid response codes as well, like 0 and 999.
if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != 501) {
return true, fmt.Errorf("unexpected HTTP status %s", resp.Status)
}
return false, nil
}
// DefaultBackoff provides a default callback for Client.Backoff which
// will perform exponential backoff based on the attempt number and limited
// by the provided minimum and maximum durations.
//
// It also tries to parse Retry-After response header when a http.StatusTooManyRequests
// (HTTP Code 429) is found in the resp parameter. Hence it will return the number of
// seconds the server states it may be ready to process more requests from this client.
func DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
if resp != nil {
if resp.StatusCode == http.StatusTooManyRequests {
if s, ok := resp.Header["Retry-After"]; ok {
if sleep, err := strconv.ParseInt(s[0], 10, 64); err == nil {
return time.Second * time.Duration(sleep)
}
}
}
}
mult := math.Pow(2, float64(attemptNum)) * float64(min)
sleep := time.Duration(mult)
if float64(sleep) != mult || sleep > max {
@ -490,25 +559,31 @@ func PassthroughErrorHandler(resp *http.Response, err error, _ int) (*http.Respo
// Do wraps calling an HTTP method with retries.
func (c *Client) Do(req *Request) (*http.Response, error) {
if c.HTTPClient == nil {
c.HTTPClient = cleanhttp.DefaultPooledClient()
}
c.clientInit.Do(func() {
if c.HTTPClient == nil {
c.HTTPClient = cleanhttp.DefaultPooledClient()
}
})
logger := c.logger()
if logger != nil {
switch v := logger.(type) {
case Logger:
v.Printf("[DEBUG] %s %s", req.Method, req.URL)
case LeveledLogger:
v.Debug("performing request", "method", req.Method, "url", req.URL)
case Logger:
v.Printf("[DEBUG] %s %s", req.Method, req.URL)
}
}
var resp *http.Response
var err error
var attempt int
var shouldRetry bool
var doErr, checkErr error
for i := 0; ; i++ {
attempt++
var code int // HTTP response code
// Always rewind the request body when non-nil.
@ -527,30 +602,30 @@ func (c *Client) Do(req *Request) (*http.Response, error) {
if c.RequestLogHook != nil {
switch v := logger.(type) {
case Logger:
c.RequestLogHook(v, req.Request, i)
case LeveledLogger:
c.RequestLogHook(hookLogger{v}, req.Request, i)
case Logger:
c.RequestLogHook(v, req.Request, i)
default:
c.RequestLogHook(nil, req.Request, i)
}
}
// Attempt the request
resp, err = c.HTTPClient.Do(req.Request)
resp, doErr = c.HTTPClient.Do(req.Request)
if resp != nil {
code = resp.StatusCode
}
// Check if we should continue with retries.
checkOK, checkErr := c.CheckRetry(req.Context(), resp, err)
shouldRetry, checkErr = c.CheckRetry(req.Context(), resp, doErr)
if err != nil {
if doErr != nil {
switch v := logger.(type) {
case Logger:
v.Printf("[ERR] %s %s request failed: %v", req.Method, req.URL, err)
case LeveledLogger:
v.Error("request failed", "error", err, "method", req.Method, "url", req.URL)
v.Error("request failed", "error", doErr, "method", req.Method, "url", req.URL)
case Logger:
v.Printf("[ERR] %s %s request failed: %v", req.Method, req.URL, doErr)
}
} else {
// Call this here to maintain the behavior of logging all requests,
@ -558,23 +633,18 @@ func (c *Client) Do(req *Request) (*http.Response, error) {
if c.ResponseLogHook != nil {
// Call the response logger function if provided.
switch v := logger.(type) {
case Logger:
c.ResponseLogHook(v, resp)
case LeveledLogger:
c.ResponseLogHook(hookLogger{v}, resp)
case Logger:
c.ResponseLogHook(v, resp)
default:
c.ResponseLogHook(nil, resp)
}
}
}
// Now decide if we should continue.
if !checkOK {
if checkErr != nil {
err = checkErr
}
c.HTTPClient.CloseIdleConnections()
return resp, err
if !shouldRetry {
break
}
// We do this before drainBody because there's no need for the I/O if
@ -585,7 +655,7 @@ func (c *Client) Do(req *Request) (*http.Response, error) {
}
// We're going to retry, consume any response to reuse the connection.
if err == nil && resp != nil {
if doErr == nil {
c.drainBody(resp.Body)
}
@ -596,10 +666,10 @@ func (c *Client) Do(req *Request) (*http.Response, error) {
}
if logger != nil {
switch v := logger.(type) {
case Logger:
v.Printf("[DEBUG] %s: retrying in %s (%d left)", desc, wait, remain)
case LeveledLogger:
v.Debug("retrying request", "request", desc, "timeout", wait, "remaining", remain)
case Logger:
v.Printf("[DEBUG] %s: retrying in %s (%d left)", desc, wait, remain)
}
}
select {
@ -608,21 +678,44 @@ func (c *Client) Do(req *Request) (*http.Response, error) {
return nil, req.Context().Err()
case <-time.After(wait):
}
// Make shallow copy of http Request so that we can modify its body
// without racing against the closeBody call in persistConn.writeLoop.
httpreq := *req.Request
req.Request = &httpreq
}
// this is the closest we have to success criteria
if doErr == nil && checkErr == nil && !shouldRetry {
return resp, nil
}
defer c.HTTPClient.CloseIdleConnections()
err := doErr
if checkErr != nil {
err = checkErr
}
if c.ErrorHandler != nil {
c.HTTPClient.CloseIdleConnections()
return c.ErrorHandler(resp, err, c.RetryMax+1)
return c.ErrorHandler(resp, err, attempt)
}
// By default, we close the response body and return an error without
// returning the response
if resp != nil {
resp.Body.Close()
c.drainBody(resp.Body)
}
// this means CheckRetry thought the request was a failure, but didn't
// communicate why
if err == nil {
return nil, fmt.Errorf("%s %s giving up after %d attempt(s)",
req.Method, req.URL, attempt)
}
c.HTTPClient.CloseIdleConnections()
return nil, fmt.Errorf("%s %s giving up after %d attempts",
req.Method, req.URL, c.RetryMax+1)
return nil, fmt.Errorf("%s %s giving up after %d attempt(s): %w",
req.Method, req.URL, attempt, err)
}
// Try to read the response body so we can reuse this connection.
@ -632,10 +725,10 @@ func (c *Client) drainBody(body io.ReadCloser) {
if err != nil {
if c.logger() != nil {
switch v := c.logger().(type) {
case Logger:
v.Printf("[ERR] error reading response body: %v", err)
case LeveledLogger:
v.Error("error reading response body", "error", err)
case Logger:
v.Printf("[ERR] error reading response body: %v", err)
}
}
}

11
vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go

@ -1,7 +1,9 @@
package retryablehttp
import (
"errors"
"net/http"
"net/url"
"sync"
)
@ -39,5 +41,12 @@ func (rt *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
}
// Execute the request.
return rt.Client.Do(retryableReq)
resp, err := rt.Client.Do(retryableReq)
// If we got an error returned by standard library's `Do` method, unwrap it
// otherwise we will wind up erroneously re-nesting the error.
if _, ok := err.(*url.Error); ok {
return resp, errors.Unwrap(err)
}
return resp, err
}

3
vendor/github.com/xanzy/go-gitlab/README.md

@ -44,6 +44,7 @@ to add new and/or missing endpoints. Currently the following services are suppor
- [x] Group Milestones
- [x] Group-Level Variables
- [x] Groups
- [x] Instance Clusters
- [x] Issue Boards
- [x] Issues
- [x] Jobs
@ -161,7 +162,7 @@ func main() {
s := &gitlab.CreateProjectSnippetOptions{
Title: gitlab.String("Dummy Snippet"),
FileName: gitlab.String("snippet.go"),
Code: gitlab.String("package main...."),
Content: gitlab.String("package main...."),
Visibility: gitlab.Visibility(gitlab.PublicVisibility),
}
_, _, err = git.ProjectSnippets.CreateSnippet(project.ID, s)

2
vendor/github.com/xanzy/go-gitlab/branches.go

@ -38,8 +38,10 @@ type Branch struct {
Protected bool `json:"protected"`
Merged bool `json:"merged"`
Default bool `json:"default"`
CanPush bool `json:"can_push"`
DevelopersCanPush bool `json:"developers_can_push"`
DevelopersCanMerge bool `json:"developers_can_merge"`
WebURL string `json:"web_url"`
}
func (b Branch) String() string {

10
vendor/github.com/xanzy/go-gitlab/client_options.go

@ -24,6 +24,16 @@ func WithCustomBackoff(backoff retryablehttp.Backoff) ClientOptionFunc {
}
}
// WithCustomLimiter injects a custom rate limiter to the client.
func WithCustomLimiter(limiter RateLimiter) ClientOptionFunc {
return func(c *Client) error {
c.configureLimiterOnce.Do(func() {
c.limiter = limiter
})
return nil
}
}
// WithCustomRetry can be used to configure a custom retry policy.
func WithCustomRetry(checkRetry retryablehttp.CheckRetry) ClientOptionFunc {
return func(c *Client) error {

13
vendor/github.com/xanzy/go-gitlab/commits.go

@ -50,6 +50,7 @@ type Commit struct {
Status *BuildStateValue `json:"status"`
LastPipeline *PipelineInfo `json:"last_pipeline"`
ProjectID int `json:"project_id"`
WebURL string `json:"web_url"`
}
// CommitStats represents the number of added and deleted files in a commit.
@ -118,11 +119,13 @@ const (
// CommitAction represents a single file action within a commit.
type CommitAction struct {
Action FileAction `url:"action" json:"action"`
FilePath string `url:"file_path" json:"file_path"`
PreviousPath string `url:"previous_path,omitempty" json:"previous_path,omitempty"`
Content string `url:"content,omitempty" json:"content,omitempty"`
Encoding string `url:"encoding,omitempty" json:"encoding,omitempty"`
Action FileAction `url:"action" json:"action"`
FilePath string `url:"file_path" json:"file_path"`
PreviousPath string `url:"previous_path,omitempty" json:"previous_path,omitempty"`
Content string `url:"content,omitempty" json:"content,omitempty"`
Encoding string `url:"encoding,omitempty" json:"encoding,omitempty"`
LastCommitID string `url:"last_commit_id,omitempty" json:"last_commit_id,omitempty"`
ExecuteFilemode bool `url:"execute_filemode,omitempty" json:"execute_filemode,omitempty"`
}
// CommitRef represents the reference of branches/tags in a commit.

1
vendor/github.com/xanzy/go-gitlab/deployments.go

@ -35,6 +35,7 @@ type Deployment struct {
Ref string `json:"ref"`
SHA string `json:"sha"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
User *ProjectUser `json:"user"`
Environment *Environment `json:"environment"`
Deployable struct {

133
vendor/github.com/xanzy/go-gitlab/epic_issues.go

@ -0,0 +1,133 @@
package gitlab
import "fmt"
// EpicIssuesService handles communication with the epic issue related methods
// of the GitLab API.
//
// GitLab API docs: https://docs.gitlab.com/ee/api/epic_issues.html
type EpicIssuesService struct {
client *Client
}
// EpicIssueAssignment contains both the epic and issue objects returned from
// Gitlab with the assignment ID.
//
// GitLab API docs: https://docs.gitlab.com/ee/api/epic_issues.html
type EpicIssueAssignment struct {
ID int `json:"id"`
Epic *Epic `json:"epic"`
Issue *Issue `json:"issue"`
}
// ListEpicIssues get a list of epic issues.
//
// Gitlab API docs:
// https://docs.gitlab.com/ee/api/epic_issues.html#list-issues-for-an-epic
func (s *EpicIssuesService) ListEpicIssues(gid interface{}, epic int, opt *ListOptions, options ...RequestOptionFunc) ([]*Issue, *Response, error) {
group, err := parseID(gid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("groups/%s/epics/%d/issues", pathEscape(group), epic)
req, err := s.client.NewRequest("GET", u, opt, options)
if err != nil {
return nil, nil, err
}
var is []*Issue
resp, err := s.client.Do(req, &is)
if err != nil {
return nil, resp, err
}
return is, resp, err
}
// AssignEpicIssue assigns an existing issue to an epic.
//
// Gitlab API Docs:
// https://docs.gitlab.com/ee/api/epic_issues.html#assign-an-issue-to-the-epic
func (s *EpicIssuesService) AssignEpicIssue(gid interface{}, epic, issue int, options ...RequestOptionFunc) (*EpicIssueAssignment, *Response, error) {
group, err := parseID(gid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("groups/%s/epics/%d/issues/%d", pathEscape(group), epic, issue)
req, err := s.client.NewRequest("POST", u, nil, options)
if err != nil {
return nil, nil, err
}
a := new(EpicIssueAssignment)
resp, err := s.client.Do(req, a)
if err != nil {
return nil, resp, err
}
return a, resp, err
}
// RemoveEpicIssue removes an issue from an epic.
//
// Gitlab API Docs:
// https://docs.gitlab.com/ee/api/epic_issues.html#remove-an-issue-from-the-epic
func (s *EpicIssuesService) RemoveEpicIssue(gid interface{}, epic, epicIssue int, options ...RequestOptionFunc) (*EpicIssueAssignment, *Response, error) {
group, err := parseID(gid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("groups/%s/epics/%d/issues/%d", pathEscape(group), epic, epicIssue)
req, err := s.client.NewRequest("DELETE", u, nil, options)
if err != nil {
return nil, nil, err
}
a := new(EpicIssueAssignment)
resp, err := s.client.Do(req, a)
if err != nil {
return nil, resp, err
}
return a, resp, err
}
// UpdateEpicIsssueAssignmentOptions describes the UpdateEpicIssueAssignment()
// options.
//
// Gitlab API Docs:
// https://docs.gitlab.com/ee/api/epic_issues.html#update-epic---issue-association
type UpdateEpicIsssueAssignmentOptions struct {
*ListOptions
MoveBeforeID *int `url:"move_before_id,omitempty" json:"move_before_id,omitempty"`
MoveAfterID *int `url:"move_after_id,omitempty" json:"move_after_id,omitempty"`
}
// UpdateEpicIssueAssignment moves an issue before or after another issue in an
// epic issue list.
//
// Gitlab API Docs:
// https://docs.gitlab.com/ee/api/epic_issues.html#update-epic---issue-association
func (s *EpicIssuesService) UpdateEpicIssueAssignment(gid interface{}, epic, epicIssue int, opt *UpdateEpicIsssueAssignmentOptions, options ...RequestOptionFunc) ([]*Issue, *Response, error) {
group, err := parseID(gid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("groups/%s/epics/%d/issues/%d", pathEscape(group), epic, epicIssue)
req, err := s.client.NewRequest("PUT", u, opt, options)
if err != nil {
return nil, nil, err
}
var is []*Issue
resp, err := s.client.Do(req, &is)
if err != nil {
return nil, resp, err
}
return is, resp, err
}

63
vendor/github.com/xanzy/go-gitlab/epics.go

@ -30,16 +30,12 @@ type Epic struct {
ID int `json:"id"`
IID int `json:"iid"`
GroupID int `json:"group_id"`
Author *EpicAuthor `json:"author"`
ParentID int `json:"parent_id"`
Title string `json:"title"`
Description string `json:"description"`
State string `json:"state"`
Upvotes int `json:"upvotes"`
Downvotes int `json:"downvotes"`
Labels []string `json:"labels"`
Title string `json:"title"`
UpdatedAt *time.Time `json:"updated_at"`
CreatedAt *time.Time `json:"created_at"`
UserNotesCount int `json:"user_notes_count"`
WebURL string `json:"web_url"`
Author *EpicAuthor `json:"author"`
StartDate *ISOTime `json:"start_date"`
StartDateIsFixed bool `json:"start_date_is_fixed"`
StartDateFixed *ISOTime `json:"start_date_fixed"`
@ -48,6 +44,13 @@ type Epic struct {
DueDateIsFixed bool `json:"due_date_is_fixed"`
DueDateFixed *ISOTime `json:"due_date_fixed"`
DueDateFromMilestones *ISOTime `json:"due_date_from_milestones"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
Labels []string `json:"labels"`
Upvotes int `json:"upvotes"`
Downvotes int `json:"downvotes"`
UserNotesCount int `json:"user_notes_count"`
URL string `json:"url"`
}
func (e Epic) String() string {
@ -59,12 +62,20 @@ func (e Epic) String() string {
// GitLab API docs: https://docs.gitlab.com/ee/api/epics.html#list-epics-for-a-group
type ListGroupEpicsOptions struct {
ListOptions
State *string `url:"state,omitempty" json:"state,omitempty"`
Labels Labels `url:"labels,comma,omitempty" json:"labels,omitempty"`
AuthorID *int `url:"author_id,omitempty" json:"author_id,omitempty"`
OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"`
Sort *string `url:"sort,omitempty" json:"sort,omitempty"`
Search *string `url:"search,omitempty" json:"search,omitempty"`
AuthorID *int `url:"author_id,omitempty" json:"author_id,omitempty"`
Labels Labels `url:"labels,comma,omitempty" json:"labels,omitempty"`
WithLabelDetails *bool `url:"with_labels_details,omitempty" json:"with_labels_details,omitempty"`
OrderBy *string `url:"order_by,omitempty" json:"order_by,omitempty"`
Sort *string `url:"sort,omitempty" json:"sort,omitempty"`
Search *string `url:"search,omitempty" json:"search,omitempty"`
State *string `url:"state,omitempty" json:"state,omitempty"`
CreatedAfter *time.Time `url:"created_after,omitempty" json:"created_after,omitempty"`
CreatedBefore *time.Time `url:"created_before,omitempty" json:"created_before,omitempty"`
UpdatedAfter *time.Time `url:"updated_after,omitempty" json:"updated_after,omitempty"`
UpdatedBefore *time.Time `url:"updated_before,omitempty" json:"updated_before,omitempty"`
IncludeAncestorGroups *bool `url:"include_ancestor_groups,omitempty" json:"include_ancestor_groups,omitempty"`
IncludeDescendantGroups *bool `url:"include_descendant_groups,omitempty" json:"include_descendant_groups,omitempty"`
MyReactionEmoji *string `url:"my_reaction_emoji,omitempty" json:"my_reaction_emoji,omitempty"`
}
// ListGroupEpics gets a list of group epics. This function accepts pagination
@ -116,6 +127,30 @@ func (s *EpicsService) GetEpic(gid interface{}, epic int, options ...RequestOpti
return e, resp, err
}
// GetEpicLinks gets all child epics of an epic.
//
// GitLab API docs: https://docs.gitlab.com/ee/api/epic_links.html
func (s *EpicsService) GetEpicLinks(gid interface{}, epic int, options ...RequestOptionFunc) ([]*Epic, *Response, error) {
group, err := parseID(gid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("groups/%s/epics/%d/epics", pathEscape(group), epic)
req, err := s.client.NewRequest("GET", u, nil, options)
if err != nil {
return nil, nil, err
}
var e []*Epic
resp, err := s.client.Do(req, &e)
if err != nil {
return nil, resp, err
}
return e, resp, err
}
// CreateEpicOptions represents the available CreateEpic() options.
//
// GitLab API docs: https://docs.gitlab.com/ee/api/epics.html#new-epic

9
vendor/github.com/xanzy/go-gitlab/event_webhook_types.go

@ -85,6 +85,7 @@ type TagEvent struct {
UserID int `json:"user_id"`
UserName string `json:"user_name"`
UserAvatar string `json:"user_avatar"`
UserEmail string `json:"user_email"`
ProjectID int `json:"project_id"`
Message string `json:"message"`
Project struct {
@ -443,8 +444,8 @@ type IssueCommentEvent struct {
TimeEstimate int `json:"time_estimate"`
Confidential bool `json:"confidential"`
TotalTimeSpent int `json:"total_time_spent"`
HumanTotalTimeSpent int `json:"human_total_time_spent"`
HumanTimeEstimate int `json:"human_time_estimate"`
HumanTotalTimeSpent string `json:"human_total_time_spent"`
HumanTimeEstimate string `json:"human_time_estimate"`
AssigneeIDs []int `json:"assignee_ids"`
AssigneeID int `json:"assignee_id"`
} `json:"issue"`
@ -593,6 +594,10 @@ type MergeEvent struct {
Previous int `json:"previous"`
Current int `json:"current"`
} `json:"source_project_id"`
StateID struct {
Previous int `json:"previous"`
Current int `json:"current"`
} `json:"state_id"`
TargetBranch struct {
Previous string `json:"previous"`
Current string `json:"current"`

496
vendor/github.com/xanzy/go-gitlab/gitlab.go

@ -20,7 +20,6 @@ package gitlab
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -63,268 +62,6 @@ const (
privateToken
)
// AccessLevelValue represents a permission level within GitLab.
//
// GitLab API docs: https://docs.gitlab.com/ce/permissions/permissions.html
type AccessLevelValue int
// List of available access levels
//
// GitLab API docs: https://docs.gitlab.com/ce/permissions/permissions.html
const (
NoPermissions AccessLevelValue = 0
GuestPermissions AccessLevelValue = 10
ReporterPermissions AccessLevelValue = 20
DeveloperPermissions AccessLevelValue = 30
MaintainerPermissions AccessLevelValue = 40
OwnerPermissions AccessLevelValue = 50
// These are deprecated and should be removed in a future version
MasterPermissions AccessLevelValue = 40
OwnerPermission AccessLevelValue = 50
)
// BuildStateValue represents a GitLab build state.
type BuildStateValue string
// These constants represent all valid build states.
const (
Pending BuildStateValue = "pending"
Created BuildStateValue = "created"
Running BuildStateValue = "running"
Success BuildStateValue = "success"
Failed BuildStateValue = "failed"
Canceled BuildStateValue = "canceled"
Skipped BuildStateValue = "skipped"
Manual BuildStateValue = "manual"
)
// DeploymentStatusValue represents a Gitlab deployment status.
type DeploymentStatusValue string
// These constants represent all valid deployment statuses.
const (
DeploymentStatusCreated DeploymentStatusValue = "created"
DeploymentStatusRunning DeploymentStatusValue = "running"
DeploymentStatusSuccess DeploymentStatusValue = "success"
DeploymentStatusFailed DeploymentStatusValue = "failed"
DeploymentStatusCanceled DeploymentStatusValue = "canceled"
)
// ISOTime represents an ISO 8601 formatted date
type ISOTime time.Time
// ISO 8601 date format
const iso8601 = "2006-01-02"
// MarshalJSON implements the json.Marshaler interface
func (t ISOTime) MarshalJSON() ([]byte, error) {
if y := time.Time(t).Year(); y < 0 || y >= 10000 {
// ISO 8901 uses 4 digits for the years
return nil, errors.New("json: ISOTime year outside of range [0,9999]")
}
b := make([]byte, 0, len(iso8601)+2)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, iso8601)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON implements the json.Unmarshaler interface
func (t *ISOTime) UnmarshalJSON(data []byte) error {
// Ignore null, like in the main JSON package
if string(data) == "null" {
return nil
}
isotime, err := time.Parse(`"`+iso8601+`"`, string(data))
*t = ISOTime(isotime)
return err
}
// EncodeValues implements the query.Encoder interface
func (t *ISOTime) EncodeValues(key string, v *url.Values) error {
if t == nil || (time.Time(*t)).IsZero() {
return nil
}
v.Add(key, t.String())
return nil
}
// String implements the Stringer interface
func (t ISOTime) String() string {
return time.Time(t).Format(iso8601)
}
// NotificationLevelValue represents a notification level.
type NotificationLevelValue int
// String implements the fmt.Stringer interface.
func (l NotificationLevelValue) String() string {
return notificationLevelNames[l]
}
// MarshalJSON implements the json.Marshaler interface.
func (l NotificationLevelValue) MarshalJSON() ([]byte, error) {
return json.Marshal(l.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (l *NotificationLevelValue) UnmarshalJSON(data []byte) error {
var raw interface{}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
switch raw := raw.(type) {
case float64:
*l = NotificationLevelValue(raw)
case string:
*l = notificationLevelTypes[raw]
case nil:
// No action needed.
default:
return fmt.Errorf("json: cannot unmarshal %T into Go value of type %T", raw, *l)
}
return nil
}
// List of valid notification levels.
const (
DisabledNotificationLevel NotificationLevelValue = iota
ParticipatingNotificationLevel
WatchNotificationLevel
GlobalNotificationLevel
MentionNotificationLevel
CustomNotificationLevel
)
var notificationLevelNames = [...]string{
"disabled",
"participating",
"watch",
"global",
"mention",
"custom",
}
var notificationLevelTypes = map[string]NotificationLevelValue{
"disabled": DisabledNotificationLevel,
"participating": ParticipatingNotificationLevel,
"watch": WatchNotificationLevel,
"global": GlobalNotificationLevel,
"mention": MentionNotificationLevel,
"custom": CustomNotificationLevel,
}
// VisibilityValue represents a visibility level within GitLab.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/
type VisibilityValue string
// List of available visibility levels.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/
const (
PrivateVisibility VisibilityValue = "private"
InternalVisibility VisibilityValue = "internal"
PublicVisibility VisibilityValue = "public"
)
// ProjectCreationLevelValue represents a project creation level within GitLab.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/
type ProjectCreationLevelValue string
// List of available project creation levels.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/
const (
NoOneProjectCreation ProjectCreationLevelValue = "noone"
MaintainerProjectCreation ProjectCreationLevelValue = "maintainer"
DeveloperProjectCreation ProjectCreationLevelValue = "developer"
)
// SubGroupCreationLevelValue represents a sub group creation level within GitLab.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/
type SubGroupCreationLevelValue string
// List of available sub group creation levels.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/
const (
OwnerSubGroupCreationLevelValue SubGroupCreationLevelValue = "owner"
MaintainerSubGroupCreationLevelValue SubGroupCreationLevelValue = "maintainer"
)
// VariableTypeValue represents a variable type within GitLab.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/
type VariableTypeValue string
// List of available variable types.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/
const (
EnvVariableType VariableTypeValue = "env_var"
FileVariableType VariableTypeValue = "file"
)
// MergeMethodValue represents a project merge type within GitLab.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#project-merge-method
type MergeMethodValue string
// List of available merge type
//
// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#project-merge-method
const (
NoFastForwardMerge MergeMethodValue = "merge"
FastForwardMerge MergeMethodValue = "ff"
RebaseMerge MergeMethodValue = "rebase_merge"
)
// EventTypeValue represents actions type for contribution events
type EventTypeValue string
// List of available action type
//
// GitLab API docs: https://docs.gitlab.com/ce/api/events.html#action-types
const (
CreatedEventType EventTypeValue = "created"
UpdatedEventType EventTypeValue = "updated"
ClosedEventType EventTypeValue = "closed"
ReopenedEventType EventTypeValue = "reopened"
PushedEventType EventTypeValue = "pushed"
CommentedEventType EventTypeValue = "commented"
MergedEventType EventTypeValue = "merged"
JoinedEventType EventTypeValue = "joined"
LeftEventType EventTypeValue = "left"
DestroyedEventType EventTypeValue = "destroyed"
ExpiredEventType EventTypeValue = "expired"
)
// EventTargetTypeValue represents actions type value for contribution events
type EventTargetTypeValue string
// List of available action type
//
// GitLab API docs: https://docs.gitlab.com/ce/api/events.html#target-types
const (
IssueEventTargetType EventTargetTypeValue = "issue"
MilestoneEventTargetType EventTargetTypeValue = "milestone"
MergeRequestEventTargetType EventTargetTypeValue = "merge_request"
NoteEventTargetType EventTargetTypeValue = "note"
ProjectEventTargetType EventTargetTypeValue = "project"
SnippetEventTargetType EventTargetTypeValue = "snippet"
UserEventTargetType EventTargetTypeValue = "user"
)
// A Client manages communication with the GitLab API.
type Client struct {
// HTTP client used to communicate with the API.
@ -338,12 +75,12 @@ type Client struct {
// disableRetries is used to disable the default retry logic.
disableRetries bool
// configLimiter is used to make sure the limiter is configured exactly
// configureLimiterOnce is used to make sure the limiter is configured exactly
// once and block all other calls until the initial (one) call is done.
configureLimiterOnce sync.Once
// Limiter is used to limit API calls and prevent 429 responses.
limiter *rate.Limiter
limiter RateLimiter
// Token type used to make authenticated API calls.
authType authType
@ -354,6 +91,9 @@ type Client struct {
// Token used to make authenticated API calls.
token string
// Protects the token field from concurrent read/write accesses.
tokenLock sync.RWMutex
// User agent used when communicating with the GitLab API.
UserAgent string
@ -373,6 +113,7 @@ type Client struct {
Deployments *DeploymentsService
Discussions *DiscussionsService
Environments *EnvironmentsService
EpicIssues *EpicIssuesService
Epics *EpicsService
Events *EventsService
Features *FeaturesService
@ -385,8 +126,11 @@ type Client struct {
GroupMilestones *GroupMilestonesService
GroupVariables *GroupVariablesService
Groups *GroupsService
InstanceCluster *InstanceClustersService
InstanceVariables *InstanceVariablesService
IssueLinks *IssueLinksService
Issues *IssuesService
IssuesStatistics *IssuesStatisticsService
Jobs *JobsService
Keys *KeysService
Labels *LabelsService
@ -406,6 +150,7 @@ type Client struct {
ProjectCluster *ProjectClustersService
ProjectImportExport *ProjectImportExportService
ProjectMembers *ProjectMembersService
ProjectMirrors *ProjectMirrorService
ProjectSnippets *ProjectSnippetsService
ProjectVariables *ProjectVariablesService
Projects *ProjectsService
@ -441,6 +186,11 @@ type ListOptions struct {
PerPage int `url:"per_page,omitempty" json:"per_page,omitempty"`
}
// RateLimiter describes the interface that all (custom) rate limiters must implement.
type RateLimiter interface {
Wait(context.Context) error
}
// NewClient returns a new GitLab API client. To use API methods which require
// authentication, provide a valid private or personal token.
func NewClient(token string, options ...ClientOptionFunc) (*Client, error) {
@ -465,11 +215,6 @@ func NewBasicAuthClient(username, password string, options ...ClientOptionFunc)
client.username = username
client.password = password
err = client.requestOAuthToken(context.Background())
if err != nil {
return nil, err
}
return client, nil
}
@ -485,22 +230,6 @@ func NewOAuthClient(token string, options ...ClientOptionFunc) (*Client, error)
return client, nil
}
func (c *Client) requestOAuthToken(ctx context.Context) error {
config := &oauth2.Config{
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("%s://%s/oauth/authorize", c.BaseURL().Scheme, c.BaseURL().Host),
TokenURL: fmt.Sprintf("%s://%s/oauth/token", c.BaseURL().Scheme, c.BaseURL().Host),
},
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, c.client)
t, err := config.PasswordCredentialsToken(ctx, c.username, c.password)
if err != nil {
return err
}
c.token = t.AccessToken
return nil
}
func newClient(options ...ClientOptionFunc) (*Client, error) {
c := &Client{UserAgent: userAgent}
@ -547,6 +276,7 @@ func newClient(options ...ClientOptionFunc) (*Client, error) {
c.Deployments = &DeploymentsService{client: c}
c.Discussions = &DiscussionsService{client: c}
c.Environments = &EnvironmentsService{client: c}
c.EpicIssues = &EpicIssuesService{client: c}
c.Epics = &EpicsService{client: c}
c.Events = &EventsService{client: c}
c.Features = &FeaturesService{client: c}
@ -559,8 +289,10 @@ func newClient(options ...ClientOptionFunc) (*Client, error) {
c.GroupMilestones = &GroupMilestonesService{client: c}
c.GroupVariables = &GroupVariablesService{client: c}
c.Groups = &GroupsService{client: c}
c.InstanceCluster = &InstanceClustersService{client: c}
c.IssueLinks = &IssueLinksService{client: c}
c.Issues = &IssuesService{client: c, timeStats: timeStats}
c.IssuesStatistics = &IssuesStatisticsService{client: c}
c.Jobs = &JobsService{client: c}
c.Keys = &KeysService{client: c}
c.Labels = &LabelsService{client: c}
@ -580,6 +312,7 @@ func newClient(options ...ClientOptionFunc) (*Client, error) {
c.ProjectCluster = &ProjectClustersService{client: c}
c.ProjectImportExport = &ProjectImportExportService{client: c}
c.ProjectMembers = &ProjectMembersService{client: c}
c.ProjectMirrors = &ProjectMirrorService{client: c}
c.ProjectSnippets = &ProjectSnippetsService{client: c}
c.ProjectVariables = &ProjectVariablesService{client: c}
c.Projects = &ProjectsService{client: c}
@ -755,13 +488,6 @@ func (c *Client) NewRequest(method, path string, opt interface{}, options []Requ
reqHeaders := make(http.Header)
reqHeaders.Set("Accept", "application/json")
switch c.authType {
case basicAuth, oAuthToken:
reqHeaders.Set("Authorization", "Bearer "+c.token)
case privateToken:
reqHeaders.Set("PRIVATE-TOKEN", c.token)
}
if c.UserAgent != "" {
reqHeaders.Set("User-Agent", c.UserAgent)
}
@ -875,23 +601,47 @@ func (c *Client) Do(req *retryablehttp.Request, v interface{}) (*Response, error
c.configureLimiterOnce.Do(func() { c.configureLimiter() })
// Wait will block until the limiter can obtain a new token.
if err := c.limiter.Wait(req.Context()); err != nil {
err := c.limiter.Wait(req.Context())
if err != nil {
return nil, err
}
// Set the correct authentication header. If using basic auth, then check
// if we already have a token and if not first authenticate and get one.
var basicAuthToken string
switch c.authType {
case basicAuth:
c.tokenLock.RLock()
basicAuthToken = c.token
c.tokenLock.RUnlock()
if basicAuthToken == "" {
// If we don't have a token yet, we first need to request one.
basicAuthToken, err = c.requestOAuthToken(req.Context(), basicAuthToken)
if err != nil {
return nil, err
}
}
req.Header.Set("Authorization", "Bearer "+basicAuthToken)
case oAuthToken:
req.Header.Set("Authorization", "Bearer "+c.token)
case privateToken:
req.Header.Set("PRIVATE-TOKEN", c.token)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized && c.authType == basicAuth {
err = c.requestOAuthToken(req.Context())
if err != nil {
resp.Body.Close()
// The token most likely expired, so we need to request a new one and try again.
if _, err := c.requestOAuthToken(req.Context(), basicAuthToken); err != nil {
return nil, err
}
return c.Do(req, v)
}
defer resp.Body.Close()
response := newResponse(resp)
@ -913,6 +663,32 @@ func (c *Client) Do(req *retryablehttp.Request, v interface{}) (*Response, error
return response, err
}
func (c *Client) requestOAuthToken(ctx context.Context, token string) (string, error) {
c.tokenLock.Lock()
defer c.tokenLock.Unlock()
// Return early if the token was updated while waiting for the lock.
if c.token != token {
return c.token, nil
}
config := &oauth2.Config{
Endpoint: oauth2.Endpoint{
AuthURL: strings.TrimSuffix(c.baseURL.String(), apiVersionPath) + "oauth/authorize",
TokenURL: strings.TrimSuffix(c.baseURL.String(), apiVersionPath) + "oauth/token",
},
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, c.client.HTTPClient)
t, err := config.PasswordCredentialsToken(ctx, c.username, c.password)
if err != nil {
return "", err
}
c.token = t.AccessToken
return c.token, nil
}
// Helper function to accept and format both the project ID or name as project
// identifier for all API calls.
func parseID(id interface{}) (string, error) {
@ -1012,129 +788,3 @@ func parseError(raw interface{}) string {
return fmt.Sprintf("failed to parse unexpected error type: %T", raw)
}
}
// Bool is a helper routine that allocates a new bool value
// to store v and returns a pointer to it.
func Bool(v bool) *bool {
p := new(bool)
*p = v
return p
}
// Int is a helper routine that allocates a new int32 value
// to store v and returns a pointer to it, but unlike Int32
// its argument value is an int.
func Int(v int) *int {
p := new(int)
*p = v
return p
}
// String is a helper routine that allocates a new string value
// to store v and returns a pointer to it.
func String(v string) *string {
p := new(string)
*p = v
return p
}
// Time is a helper routine that allocates a new time.Time value
// to store v and returns a pointer to it.
func Time(v time.Time) *time.Time {
p := new(time.Time)
*p = v
return p
}
// AccessLevel is a helper routine that allocates a new AccessLevelValue
// to store v and returns a pointer to it.
func AccessLevel(v AccessLevelValue) *AccessLevelValue {
p := new(AccessLevelValue)
*p = v
return p
}
// BuildState is a helper routine that allocates a new BuildStateValue
// to store v and returns a pointer to it.
func BuildState(v BuildStateValue) *BuildStateValue {
p := new(BuildStateValue)
*p = v
return p
}
// DeploymentStatus is a helper routine that allocates a new
// DeploymentStatusValue to store v and returns a pointer to it.
func DeploymentStatus(v DeploymentStatusValue) *DeploymentStatusValue {
p := new(DeploymentStatusValue)
*p = v
return p
}
// NotificationLevel is a helper routine that allocates a new NotificationLevelValue
// to store v and returns a pointer to it.
func NotificationLevel(v NotificationLevelValue) *NotificationLevelValue {
p := new(NotificationLevelValue)
*p = v
return p
}
// VariableType is a helper routine that allocates a new VariableTypeValue
// to store v and returns a pointer to it.
func VariableType(v VariableTypeValue) *VariableTypeValue {
p := new(VariableTypeValue)
*p = v
return p
}
// Visibility is a helper routine that allocates a new VisibilityValue
// to store v and returns a pointer to it.
func Visibility(v VisibilityValue) *VisibilityValue {
p := new(VisibilityValue)
*p = v
return p
}
// ProjectCreationLevel is a helper routine that allocates a new ProjectCreationLevelValue
// to store v and returns a pointer to it.
func ProjectCreationLevel(v ProjectCreationLevelValue) *ProjectCreationLevelValue {
p := new(ProjectCreationLevelValue)
*p = v
return p
}
// SubGroupCreationLevel is a helper routine that allocates a new SubGroupCreationLevelValue
// to store v and returns a pointer to it.
func SubGroupCreationLevel(v SubGroupCreationLevelValue) *SubGroupCreationLevelValue {
p := new(SubGroupCreationLevelValue)
*p = v
return p
}
// MergeMethod is a helper routine that allocates a new MergeMethod
// to sotre v and returns a pointer to it.
func MergeMethod(v MergeMethodValue) *MergeMethodValue {