2021-07-12 16:58:48 +02:00
|
|
|
package sonarqube_sdk
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
2021-10-09 18:09:54 +02:00
|
|
|
"encoding/json"
|
2021-10-03 17:57:22 +02:00
|
|
|
"fmt"
|
2021-07-12 16:58:48 +02:00
|
|
|
"io"
|
2021-10-03 17:57:22 +02:00
|
|
|
"net/http"
|
2021-07-12 16:58:48 +02:00
|
|
|
|
|
|
|
"gitea-sonarqube-pr-bot/internal/settings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type SonarQubeSdkInterface interface {
|
2021-10-09 18:09:54 +02:00
|
|
|
GetMeasures(string, string) (*MeasuresResponse, error)
|
2021-07-12 16:58:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type SonarQubeSdk struct {
|
2021-10-03 17:57:22 +02:00
|
|
|
client *http.Client
|
2021-07-12 16:58:48 +02:00
|
|
|
baseUrl string
|
2021-10-03 17:57:22 +02:00
|
|
|
token string
|
2021-07-12 16:58:48 +02:00
|
|
|
}
|
|
|
|
|
2021-10-09 18:09:54 +02:00
|
|
|
func (sdk *SonarQubeSdk) GetMeasures(project string, branch string) (*MeasuresResponse, error) {
|
2021-10-09 20:44:09 +02:00
|
|
|
url := fmt.Sprintf("%s/api/measures/component?additionalFields=metrics&metricKeys=bugs,vulnerabilities,new_security_hotspots,code_smells&component=%s&pullRequest=%s", sdk.baseUrl, project, branch)
|
2021-10-09 18:09:54 +02:00
|
|
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
2021-07-12 16:58:48 +02:00
|
|
|
if err != nil {
|
2021-10-09 18:09:54 +02:00
|
|
|
return nil, fmt.Errorf("cannot initialize Request: %w", err)
|
2021-07-12 16:58:48 +02:00
|
|
|
}
|
|
|
|
req.Header.Add("Authorization", sdk.basicAuth())
|
2021-10-09 18:09:54 +02:00
|
|
|
rawResp, _ := sdk.client.Do(req)
|
|
|
|
if rawResp.Body != nil {
|
|
|
|
defer rawResp.Body.Close()
|
|
|
|
}
|
2021-07-12 16:58:48 +02:00
|
|
|
|
2021-10-09 18:09:54 +02:00
|
|
|
body, _ := io.ReadAll(rawResp.Body)
|
|
|
|
response := &MeasuresResponse{}
|
|
|
|
err = json.Unmarshal(body, &response)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot parse response from SonarQube: %w", err)
|
|
|
|
}
|
2021-07-12 16:58:48 +02:00
|
|
|
|
2021-10-09 18:09:54 +02:00
|
|
|
return response, nil
|
2021-07-12 16:58:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (sdk *SonarQubeSdk) basicAuth() string {
|
|
|
|
auth := []byte(fmt.Sprintf("%s:", sdk.token))
|
|
|
|
return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString(auth))
|
|
|
|
}
|
|
|
|
|
|
|
|
func New() *SonarQubeSdk {
|
|
|
|
return &SonarQubeSdk{
|
2021-10-03 17:57:22 +02:00
|
|
|
client: &http.Client{},
|
2021-07-12 16:58:48 +02:00
|
|
|
baseUrl: settings.SonarQube.Url,
|
2021-10-03 17:57:22 +02:00
|
|
|
token: settings.SonarQube.Token.Value,
|
2021-07-12 16:58:48 +02:00
|
|
|
}
|
|
|
|
}
|