Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: action github create comment for sql review results (#15862)
p0ny9b5f6a66d57c
diff --git a/action/github.go b/action/github.godeleted file mode 100644index 86a4d0a913..0000000000--- a/action/github.go+++ /dev/null@@ -1,47 +0,0 @@-package main--import (- "fmt"- "strings"-- v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"-)--func writeAnnotations(resp *v1pb.CheckReleaseResponse) error {- // annotation template- // `::${advice.status} file=${file},line=${advice.line},col=${advice.column},title=${advice.title} (${advice.code})::${advice.content}. Targets: ${targets.join(', ')} https://www.bytebase.com/docs/reference/error-code/advisor#${advice.code}`- for _, result := range resp.Results {- for _, advice := range result.Advices {- var sb strings.Builder- _, _ = sb.WriteString("::")- switch advice.Status {- case v1pb.Advice_WARNING:- _, _ = sb.WriteString("warning ")- case v1pb.Advice_ERROR:- _, _ = sb.WriteString("error ")- default:- continue- }-- _, _ = sb.WriteString(" file=")- _, _ = sb.WriteString(result.File)- _, _ = sb.WriteString(",line=")- _, _ = sb.WriteString(string(advice.Line))- _, _ = sb.WriteString(",col=")- _, _ = sb.WriteString(string(advice.Column))- _, _ = sb.WriteString(",title=")- _, _ = sb.WriteString(advice.Title)- _, _ = sb.WriteString(" (")- _, _ = sb.WriteString(string(advice.Code))- _, _ = sb.WriteString(")::")- _, _ = sb.WriteString(advice.Content)- _, _ = sb.WriteString(". Targets: ")- _, _ = sb.WriteString(result.Target)- _, _ = sb.WriteString(" ")- _, _ = sb.WriteString(" https://www.bytebase.com/docs/reference/error-code/advisor#")- _, _ = sb.WriteString(string(advice.Code))- fmt.Println(sb.String())- }- }- return nil-}diff --git a/action/github/api.go b/action/github/api.gonew file mode 100644index 0000000000..a4d92b8eec--- /dev/null+++ b/action/github/api.go@@ -0,0 +1,129 @@+package github++import (+ "bytes"+ "encoding/json"+ "fmt"+ "io"+ "net/http"++ "github.com/pkg/errors"+)++type githubClient struct {+ apiURL string+ token string+ client *http.Client+}++type comment struct {+ ID int64 `json:"id"`+ Body string `json:"body"`+ User struct {+ ID int64 `json:"id"`+ } `json:"user"`+}++func newClient(apiURL, token string) *githubClient {+ return &githubClient{+ apiURL: apiURL,+ token: token,+ client: &http.Client{},+ }+}++func (g *githubClient) createComment(repo, pr, msg string) error {+ body := map[string]string{+ "body": msg,+ }+ bodyBytes, err := json.Marshal(body)+ if err != nil {+ return errors.Wrap(err, "failed to marshal request body")+ }++ url := fmt.Sprintf("%s/repos/%s/issues/%s/comments", g.apiURL, repo, pr)+ req, err := http.NewRequest("POST", url, bytes.NewReader(bodyBytes))+ if err != nil {+ return errors.Wrap(err, "failed to create request")+ }+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", g.token))+ req.Header.Set("Accept", "application/vnd.github.raw+json")+ req.Header.Set("X-GitHub-Api-Version", "2022-11-28")++ resp, err := g.client.Do(req)+ if err != nil {+ return errors.Wrap(err, "failed to send request")+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusCreated {+ return errors.Errorf("failed to create comment, status code: %d", resp.StatusCode)+ }++ return nil+}++func (g *githubClient) listComments(repo, pr string) ([]comment, error) {+ url := fmt.Sprintf("%s/repos/%s/issues/%s/comments", g.apiURL, repo, pr)+ req, err := http.NewRequest("GET", url, nil)+ if err != nil {+ return nil, errors.Wrap(err, "failed to create request")+ }+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", g.token))+ req.Header.Set("Accept", "application/vnd.github.raw+json")+ req.Header.Set("X-GitHub-Api-Version", "2022-11-28")++ resp, err := g.client.Do(req)+ if err != nil {+ return nil, errors.Wrap(err, "failed to send request")+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ bodyBytes, _ := io.ReadAll(resp.Body)+ return nil, errors.Errorf("failed to list comments: %s", string(bodyBytes))+ }++ bodyBytes, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, errors.Wrap(err, "failed to read response body")+ }++ var comments []comment+ if err := json.Unmarshal(bodyBytes, &comments); err != nil {+ return nil, errors.Wrap(err, "failed to unmarshal response body")+ }++ return comments, nil+}++func (g *githubClient) updateComment(repo string, commentID int64, msg string) error {+ body := map[string]string{+ "body": msg,+ }+ bodyBytes, err := json.Marshal(body)+ if err != nil {+ return errors.Wrap(err, "failed to marshal request body")+ }++ url := fmt.Sprintf("%s/repos/%s/issues/comments/%d", g.apiURL, repo, commentID)+ req, err := http.NewRequest("PATCH", url, bytes.NewReader(bodyBytes))+ if err != nil {+ return errors.Wrap(err, "failed to create request")+ }+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", g.token))+ req.Header.Set("Accept", "application/vnd.github.raw+json")+ req.Header.Set("X-GitHub-Api-Version", "2022-11-28")++ resp, err := g.client.Do(req)+ if err != nil {+ return errors.Wrap(err, "failed to send request")+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return errors.Errorf("failed to update comment, status code: %d", resp.StatusCode)+ }++ return nil+}diff --git a/action/github/github.go b/action/github/github.gonew file mode 100644index 0000000000..d81eb32115--- /dev/null+++ b/action/github/github.go@@ -0,0 +1,188 @@+package github++import (+ "fmt"+ "strings"++ "github.com/caarlos0/env/v11"+ "github.com/pkg/errors"++ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"+)++const maxCommentLength = 65536+const commentHeader = `<!--BYTEBASE_MARKER-DO_NOT_EDIT-->`+const githubActionUserID = 41898282++type githubEnv struct {+ APIUrl string `env:"GITHUB_API_URL,required,notEmpty"`+ Repo string `env:"GITHUB_REPOSITORY,required,notEmpty"`+ PR string `env:"GITHUB_PR_NUMBER"`+ Token string `env:"GITHUB_TOKEN,required,notEmpty"`+}++func CreateCommentAndAnnotation(resp *v1pb.CheckReleaseResponse) error {+ ghe, err := env.ParseAs[githubEnv]()+ if err != nil {+ return errors.Wrap(err, "failed to parse GitHub environment variables")+ }+ // Write annotations to the pull request.+ if err := writeAnnotations(resp); err != nil {+ return err+ }+ // Upsert a comment on the pull request with the check results.+ if err := upsertComment(resp, &ghe); err != nil {+ fmt.Printf("failed to upsert comment on the pull request: %v\n", err)+ return nil+ }+ return nil+}++func upsertComment(resp *v1pb.CheckReleaseResponse, ghe *githubEnv) error {+ if ghe.PR == "" {+ fmt.Println("No pull request number found in the environment variables.\nI won't create a comment.\nPass GITHUB_PR_NUMBER to create a comment.")+ return nil+ }+ // upsert the comment+ c := newClient(ghe.APIUrl, ghe.Token)+ comments, err := c.listComments(ghe.Repo, ghe.PR)+ if err != nil {+ return errors.Wrapf(err, "failed to list comments")+ }+ for _, comment := range comments {+ if comment.User.ID == githubActionUserID && strings.HasPrefix(comment.Body, commentHeader) {+ // update the comment+ if err := c.updateComment(ghe.Repo, comment.ID, buildCommentMessage(resp)); err != nil {+ return errors.Wrapf(err, "failed to update comment")+ }+ return nil+ }+ }++ // create a new comment+ if err := c.createComment(ghe.Repo, ghe.PR, buildCommentMessage(resp)); err != nil {+ return errors.Wrapf(err, "failed to create comment")+ }+ return nil+}++func buildCommentMessage(resp *v1pb.CheckReleaseResponse) string {+ var errorCount, warningCount int+ for _, result := range resp.Results {+ for _, advice := range result.Advices {+ switch advice.Status {+ case v1pb.Advice_WARNING:+ warningCount+++ case v1pb.Advice_ERROR:+ errorCount+++ }+ }+ }++ var sb strings.Builder+ _, _ = sb.WriteString(commentHeader + "\n")+ _, _ = sb.WriteString("## SQL Review Summary\n\n")+ _, _ = sb.WriteString(fmt.Sprintf("* Total Affected Rows: **%d**\n", resp.AffectedRows))+ _, _ = sb.WriteString(fmt.Sprintf("* Overall Risk Level: **%s**\n", formatRiskLevel(resp.RiskLevel)))+ _, _ = sb.WriteString(fmt.Sprintf("* Advices Statistics: **%d Error(s), %d Warning(s)**\n", errorCount, warningCount))+ _, _ = sb.WriteString("### Detailed Results\n")+ _, _ = sb.WriteString(`+<table>+ <thead>+ <tr>+ <th>File</th>+ <th>Target</th>+ <th>Affected Rows</th>+ <th>Risk Level</th>+ <th>Advices</th>+ </tr>+ </thead>+ <tbody>`)+ for _, result := range resp.Results {+ if sb.Len() > maxCommentLength-1000 {+ break+ }+ var errorCount, warningCount int+ for _, advice := range result.Advices {+ switch advice.Status {+ case v1pb.Advice_WARNING:+ warningCount+++ case v1pb.Advice_ERROR:+ errorCount+++ }+ }+ counts := []string{}+ if errorCount > 0 {+ counts = append(counts, fmt.Sprintf("%d Error(s)", errorCount))+ }+ if warningCount > 0 {+ counts = append(counts, fmt.Sprintf("%d Warning(s)", warningCount))+ }+ adviceCell := "-"+ if len(counts) > 0 {+ adviceCell = strings.Join(counts, ", ")+ }++ _, _ = sb.WriteString(fmt.Sprintf(`<tr>+<td>%s</td>+<td>%s</td>+<td>%d</td>+<td>%s</td>+<td>%s</td>+</tr>`, result.File, result.Target, result.AffectedRows, formatRiskLevel(result.RiskLevel), adviceCell))+ }+ _, _ = sb.WriteString("</tbody></table>")+ return sb.String()+}++func writeAnnotations(resp *v1pb.CheckReleaseResponse) error {+ // annotation template+ // `::${advice.status} file=${file},line=${advice.line},col=${advice.column},title=${advice.title} (${advice.code})::${advice.content}. Targets: ${targets.join(', ')} https://www.bytebase.com/docs/reference/error-code/advisor#${advice.code}`+ for _, result := range resp.Results {+ for _, advice := range result.Advices {+ var sb strings.Builder+ _, _ = sb.WriteString("::")+ switch advice.Status {+ case v1pb.Advice_WARNING:+ _, _ = sb.WriteString("warning ")+ case v1pb.Advice_ERROR:+ _, _ = sb.WriteString("error ")+ default:+ continue+ }++ _, _ = sb.WriteString(" file=")+ _, _ = sb.WriteString(result.File)+ _, _ = sb.WriteString(",line=")+ _, _ = sb.WriteString(string(advice.Line))+ _, _ = sb.WriteString(",col=")+ _, _ = sb.WriteString(string(advice.Column))+ _, _ = sb.WriteString(",title=")+ _, _ = sb.WriteString(advice.Title)+ _, _ = sb.WriteString(" (")+ _, _ = sb.WriteString(string(advice.Code))+ _, _ = sb.WriteString(")::")+ _, _ = sb.WriteString(advice.Content)+ _, _ = sb.WriteString(". Targets: ")+ _, _ = sb.WriteString(result.Target)+ _, _ = sb.WriteString(" ")+ _, _ = sb.WriteString(" https://www.bytebase.com/docs/reference/error-code/advisor#")+ _, _ = sb.WriteString(string(advice.Code))+ fmt.Println(sb.String())+ }+ }+ return nil+}++func formatRiskLevel(r v1pb.CheckReleaseResponse_RiskLevel) string {+ switch r {+ case v1pb.CheckReleaseResponse_LOW:+ return "🟢 Low"+ case v1pb.CheckReleaseResponse_MODERATE:+ return "🟡 Moderate"+ case v1pb.CheckReleaseResponse_HIGH:+ return "🔴 High"+ default:+ return "⚪ None"+ }+}diff --git a/action/main.go b/action/main.goindex afe2a48e5c..5c39a05994 100644--- a/action/main.go+++ b/action/main.go@@ -7,6 +7,7 @@ import ("github.com/pkg/errors"+ "github.com/bytebase/bytebase/action/github"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -51,7 +52,7 @@ func run(platform JobPlatform) error {}switch platform {case GitHub:- if err := writeAnnotations(checkReleaseResponse); err != nil {+ if err := github.CreateCommentAndAnnotation(checkReleaseResponse); err != nil {return err}case GitLab:diff --git a/go.mod b/go.modindex 175aeda1f5..babeef8ae4 100644--- a/go.mod+++ b/go.mod@@ -35,6 +35,7 @@ require (github.com/bytebase/postgresql-parser v0.0.0-20250213053010-aeb8220eb3bbgithub.com/bytebase/snowsql-parser v0.0.0-20250124075214-562d62e69c35github.com/bytebase/tidb-parser v0.0.0-20240821091609-162fffe2a839+ github.com/caarlos0/env/v11 v11.3.1github.com/cenkalti/backoff/v4 v4.3.0github.com/cockroachdb/cockroachdb-parser v0.23.2github.com/coreos/go-oidc v2.3.0+incompatiblediff --git a/go.sum b/go.sumindex 68442fca25..6909bc2154 100644--- a/go.sum+++ b/go.sum@@ -872,6 +872,8 @@ github.com/bytebase/tidb2/pkg/parser v0.0.0-20231129002249-5bbb6bb83940 h1:PZ22Fgithub.com/bytebase/tidb2/pkg/parser v0.0.0-20231129002249-5bbb6bb83940/go.mod h1:yRkiqLFwIqibYg2P7h4bclHjHcJiIFRLKhGRyBcKYus=github.com/bytebase/tsql-parser v0.0.0-20250311085620-1db45111863e h1:R7yllkuKkKLbsbZx/OPN985g3QWHrwz4ixq7OGnn2Tw=github.com/bytebase/tsql-parser v0.0.0-20250311085620-1db45111863e/go.mod h1:L9qgmrnVenkm/SL/fmyUSXK5+iMT1ctn/EsMqItSGVk=+github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=+github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=github.com/cenkalti/backoff/v3 v3.0.0/go.mod h1:cIeZDE3IrqwwJl6VUwCN6trj1oXrTS4rc0ij+ULvLYs=