/
server_api_client.go
99 lines (78 loc) 路 2.55 KB
/
server_api_client.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
package bitbucket
import (
"context"
"fmt"
"io"
"net/http"
insights "github.com/reva2/bitbucket-insights-api"
)
// ServerAPIClient is wrapper for Bitbucket Server Code Insights API client
type ServerAPIClient struct {
cli *insights.APIClient
helper *ServerAPIHelper
}
// NewServerAPIClient creates client for Bitbucket Server Code Insights API
func NewServerAPIClient() APIClient {
httpClient := &http.Client{
Timeout: httpTimeout,
}
config := insights.NewConfiguration()
config.HTTPClient = httpClient
return &ServerAPIClient{
cli: insights.NewAPIClient(config),
helper: &ServerAPIHelper{},
}
}
// CreateOrUpdateReport creates or updates specified report
func (c *ServerAPIClient) CreateOrUpdateReport(ctx context.Context, req *ReportRequest) error {
// Bitbucket Server API doesn't support pending status
if req.Result == reportResultPending {
return nil
}
// We need to drop report and delete all annotations created previously
err := c.deleteReport(ctx, req)
if err != nil {
return err
}
_, resp, err := c.cli.InsightsApi.
UpdateReport(ctx, req.Owner, req.Repository, req.Commit, req.ReportID).
Report(c.helper.BuildReport(req)).
Execute()
if err := c.checkAPIError(err, resp, http.StatusOK); err != nil {
return fmt.Errorf("failed to create code insights report: %w", err)
}
return nil
}
// CreateOrUpdateAnnotations creates or updates annotations
func (c *ServerAPIClient) CreateOrUpdateAnnotations(ctx context.Context, req *AnnotationsRequest) error {
resp, err := c.cli.InsightsApi.
CreateAnnotations(ctx, req.Owner, req.Repository, req.Commit, req.ReportID).
AnnotationsList(c.helper.BuildAnnotations(req.Comments)).
Execute()
if err := c.checkAPIError(err, resp, http.StatusNoContent); err != nil {
return fmt.Errorf("failed to create annotations: %w", err)
}
return nil
}
func (c *ServerAPIClient) deleteReport(ctx context.Context, report *ReportRequest) error {
resp, err := c.cli.InsightsApi.
DeleteReport(ctx, report.Owner, report.Repository, report.Commit, report.ReportID).
Execute()
if err := c.checkAPIError(err, resp, http.StatusNoContent); err != nil {
return fmt.Errorf("failed to delete code insights report: %w", err)
}
return nil
}
func (c *ServerAPIClient) checkAPIError(err error, resp *http.Response, expectedCode int) error {
if err != nil {
return fmt.Errorf("bitbucket Server API error: %w", err)
}
if resp != nil && resp.StatusCode != expectedCode {
body, _ := io.ReadAll(resp.Body)
return UnexpectedResponseError{
Code: resp.StatusCode,
Body: body,
}
}
return nil
}