github.com/reviewdog/reviewdog@v0.17.5-0.20240516205324-0cd103a83d58/service/bitbucket/server_api_context.go (about) 1 package bitbucket 2 3 import ( 4 "context" 5 "fmt" 6 "net/url" 7 8 insights "github.com/reva2/bitbucket-insights-api" 9 ) 10 11 // BuildServerAPIContext builds context.Context used to call Bitbucket Server Code Insights API 12 func BuildServerAPIContext(ctx context.Context, bbURL, user, password, token string) (context.Context, error) { 13 var err error 14 ctx, err = withServerVariables(ctx, bbURL) 15 if err != nil { 16 return ctx, err 17 } 18 19 if user != "" && password != "" { 20 ctx = withServerBasicAuth(ctx, user, password) 21 } 22 23 if token != "" { 24 ctx = withServerAccessToken(ctx, token) 25 } 26 27 return ctx, nil 28 } 29 30 // WithServerBasicAuth adds basic auth credentials to context 31 func withServerBasicAuth(ctx context.Context, user, password string) context.Context { 32 return context.WithValue(ctx, insights.ContextBasicAuth, insights.BasicAuth{ 33 UserName: user, 34 Password: password, 35 }) 36 } 37 38 // WithServerAccessToken adds basic auth credentials to context 39 func withServerAccessToken(ctx context.Context, token string) context.Context { 40 return context.WithValue(ctx, insights.ContextAccessToken, token) 41 } 42 43 // WithServerVariables adds server variable to context 44 func withServerVariables(ctx context.Context, bbURL string) (context.Context, error) { 45 parsed, err := url.Parse(bbURL) 46 if err != nil { 47 return ctx, fmt.Errorf("failed to parse Bitbucket Server URL: %w", err) 48 } 49 50 if parsed.Scheme == "" { 51 return ctx, fmt.Errorf("unable to determine scheme of Bitbucket Server URL: %w", err) 52 } 53 54 if parsed.Host == "" { 55 return ctx, fmt.Errorf("unable to determine host of Bitbucket Server URL: %w", err) 56 } 57 58 return context.WithValue( 59 ctx, 60 insights.ContextServerVariables, 61 map[string]string{ 62 "protocol": parsed.Scheme, 63 "bitbucketDomain": parsed.Host + parsed.Path, 64 }, 65 ), nil 66 }