• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mindersec / minder / 23956728772

03 Apr 2026 06:09PM UTC coverage: 58.182% (-0.1%) from 58.315%
23956728772

Pull #6262

github

web-flow
Merge 35d3b8e0a into 1760b5d40
Pull Request #6262: Decouple PR feedback actions from GitHub-specific provider

99 of 231 new or added lines in 5 files covered. (42.86%)

159 existing lines in 4 files now uncovered.

19309 of 33187 relevant lines covered (58.18%)

36.03 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

51.59
/internal/engine/actions/alert/pull_request_comment/pull_request_comment.go
1
// SPDX-FileCopyrightText: Copyright 2024 The Minder Authors
2
// SPDX-License-Identifier: Apache-2.0
3

4
// Package pull_request_comment provides necessary interfaces and implementations for
5
// processing pull request comment alerts.
6
package pull_request_comment
7

8
import (
9
        "context"
10
        "encoding/json"
11
        "errors"
12
        "fmt"
13
        "math"
14
        "strconv"
15
        "time"
16

17
        "github.com/google/go-github/v63/github"
18
        "github.com/rs/zerolog"
19
        "google.golang.org/protobuf/reflect/protoreflect"
20

21
        "github.com/mindersec/minder/internal/db"
22
        enginerr "github.com/mindersec/minder/internal/engine/errors"
23
        "github.com/mindersec/minder/internal/engine/interfaces"
24
        pbinternal "github.com/mindersec/minder/internal/proto"
25
        "github.com/mindersec/minder/internal/util"
26
        pb "github.com/mindersec/minder/pkg/api/protobuf/go/minder/v1"
27
        "github.com/mindersec/minder/pkg/profiles/models"
28
        provifv1 "github.com/mindersec/minder/pkg/providers/v1"
29
)
30

31
const (
32
        // AlertType is the type of the pull request comment alert engine
33
        AlertType = "pull_request_comment"
34
        // PrCommentMaxLength is the maximum length of the pull request comment
35
        // (this was derived from the limit of the GitHub API)
36
        PrCommentMaxLength = 65536
37
)
38

39
// Alert is the structure backing the noop alert
40
type Alert struct {
41
        actionType interfaces.ActionType
42
        gh         provifv1.ReviewPublisher
43
        reviewCfg  *pb.RuleType_Definition_Alert_AlertTypePRComment
44
        setting    models.ActionOpt
45
}
46

47
// PrCommentTemplateParams is the parameters for the PR comment templates
48
type PrCommentTemplateParams struct {
49
        // EvalErrorDetails is the details of the error that occurred during evaluation, which may be empty
50
        EvalErrorDetails string
51

52
        // EvalResult is the output of the evaluation, which may be empty
53
        EvalResultOutput any
54
}
55

56
type paramsPR struct {
57
        Owner      string
58
        Repo       string
59
        CommitSha  string
60
        Number     int
61
        Comment    string
62
        Metadata   *alertMetadata
63
        prevStatus *db.ListRuleEvaluationsByProfileIdRow
64
}
65

66
type alertMetadata struct {
67
        ReviewID       string     `json:"review_id,omitempty"`
68
        SubmittedAt    *time.Time `json:"submitted_at,omitempty"`
69
        PullRequestUrl *string    `json:"pull_request_url,omitempty"`
70
}
71

72
// NewPullRequestCommentAlert creates a new pull request comment alert action
73
func NewPullRequestCommentAlert(
74
        actionType interfaces.ActionType,
75
        reviewCfg *pb.RuleType_Definition_Alert_AlertTypePRComment,
76
        gh provifv1.ReviewPublisher,
77
        setting models.ActionOpt,
78
) (*Alert, error) {
5✔
79
        if actionType == "" {
5✔
UNCOV
80
                return nil, fmt.Errorf("action type cannot be empty")
×
81
        }
×
82

83
        return &Alert{
5✔
84
                actionType: actionType,
5✔
85
                gh:         gh,
5✔
86
                reviewCfg:  reviewCfg,
5✔
87
                setting:    setting,
5✔
88
        }, nil
5✔
89
}
90

91
// Class returns the action type of the PR comment alert engine
92
func (alert *Alert) Class() interfaces.ActionType {
1✔
93
        return alert.actionType
1✔
94
}
1✔
95

96
// Type returns the action subtype of the PR comment alert engine
UNCOV
97
func (*Alert) Type() string {
×
UNCOV
98
        return AlertType
×
UNCOV
99
}
×
100

101
// GetOnOffState returns the alert action state read from the profile
102
func (alert *Alert) GetOnOffState() models.ActionOpt {
×
103
        return models.ActionOptOrDefault(alert.setting, models.ActionOptOff)
×
UNCOV
104
}
×
105

106
// Do comments on a pull request
107
func (alert *Alert) Do(
108
        ctx context.Context,
109
        cmd interfaces.ActionCmd,
110
        entity protoreflect.ProtoMessage,
111
        params interfaces.ActionsParams,
112
        metadata *json.RawMessage,
113
) (json.RawMessage, error) {
5✔
114
        pr, ok := entity.(*pbinternal.PullRequest)
5✔
115
        if !ok {
5✔
UNCOV
116
                return nil, fmt.Errorf("expected pull request, got %T", entity)
×
UNCOV
117
        }
×
118

119
        commentParams, err := alert.getParamsForPRComment(ctx, pr, params, metadata)
5✔
120
        if err != nil {
5✔
121
                return nil, fmt.Errorf("error extracting parameters for PR comment: %w", err)
×
UNCOV
122
        }
×
123

124
        // Process the command based on the action setting
125
        switch alert.setting {
5✔
126
        case models.ActionOptOn:
5✔
127
                return alert.run(ctx, commentParams, cmd)
5✔
UNCOV
128
        case models.ActionOptDryRun:
×
UNCOV
129
                return alert.runDry(ctx, commentParams, cmd)
×
UNCOV
130
        case models.ActionOptOff, models.ActionOptUnknown:
×
UNCOV
131
                return nil, fmt.Errorf("unexpected action setting: %w", enginerr.ErrActionFailed)
×
132
        }
133
        return nil, enginerr.ErrActionSkipped
×
134
}
135

136
func (alert *Alert) run(ctx context.Context, params *paramsPR, cmd interfaces.ActionCmd) (json.RawMessage, error) {
5✔
137
        logger := zerolog.Ctx(ctx)
5✔
138

5✔
139
        // Process the command
5✔
140
        switch cmd {
5✔
141
        // Create a review
142
        case interfaces.ActionCmdOn:
4✔
143
                if err := alert.gh.PublishReview(ctx, params.Owner, params.Repo, params.Number,
4✔
144
                        &provifv1.Review{Body: params.Comment}); err != nil {
5✔
145
                        return nil, fmt.Errorf("error creating PR review: %w, %w", err, enginerr.ErrActionFailed)
1✔
146
                }
1✔
147

148
                now := time.Now()
3✔
149
                newMeta, err := json.Marshal(alertMetadata{
3✔
150
                        SubmittedAt: &now,
3✔
151
                })
3✔
152
                if err != nil {
3✔
153
                        return nil, fmt.Errorf("error marshalling alert metadata json: %w", err)
×
154
                }
×
155

156
                logger.Info().Msg("PR review created")
3✔
157
                return newMeta, nil
3✔
158
        // Dismiss the review
159
        case interfaces.ActionCmdOff:
1✔
160
                if params.Metadata == nil || params.Metadata.ReviewID == "" {
1✔
161
                        // We cannot do anything without the PR review ID, so we assume that turning the alert off is a success
×
162
                        return nil, fmt.Errorf("no PR comment ID provided: %w", enginerr.ErrActionTurnedOff)
×
163
                }
×
164

165
                reviewID, err := strconv.ParseInt(params.Metadata.ReviewID, 10, 64)
1✔
166
                if err != nil {
1✔
167
                        zerolog.Ctx(ctx).Error().Err(err).Str("review_id", params.Metadata.ReviewID).Msg("failed to parse review_id")
×
168
                        return nil, fmt.Errorf("no PR comment ID provided: %w, %w", err, enginerr.ErrActionTurnedOff)
×
169
                }
×
170

171
                if err := alert.gh.DismissPublishedReview(ctx, params.Owner, params.Repo, params.Number, reviewID,
1✔
172
                        "Dismissed due to alert being turned off"); err != nil {
1✔
173
                        if errors.Is(err, enginerr.ErrNotFound) {
×
174
                                // There's no PR review with that ID anymore.
×
UNCOV
175
                                // We exit by stating that the action was turned off.
×
UNCOV
176
                                return nil, fmt.Errorf("PR comment already dismissed: %w, %w", err, enginerr.ErrActionTurnedOff)
×
177
                        }
×
UNCOV
178
                        return nil, fmt.Errorf("error dismissing PR comment: %w, %w", err, enginerr.ErrActionFailed)
×
179
                }
180
                logger.Info().Str("review_id", params.Metadata.ReviewID).Msg("PR comment dismissed")
1✔
181
                // Success - return ErrActionTurnedOff to indicate the action was successful
1✔
182
                return nil, fmt.Errorf("%s : %w", alert.Class(), enginerr.ErrActionTurnedOff)
1✔
183
        case interfaces.ActionCmdDoNothing:
×
UNCOV
184
                // Return the previous alert status.
×
UNCOV
185
                return alert.runDoNothing(ctx, params)
×
186
        }
UNCOV
187
        return nil, enginerr.ErrActionSkipped
×
188
}
189

190
// runDry runs the pull request comment action in dry run mode, which logs the comment that would be made
191
func (alert *Alert) runDry(ctx context.Context, params *paramsPR, cmd interfaces.ActionCmd) (json.RawMessage, error) {
×
UNCOV
192
        logger := zerolog.Ctx(ctx)
×
UNCOV
193

×
194
        // Process the command
×
195
        switch cmd {
×
196
        case interfaces.ActionCmdOn:
×
UNCOV
197
                body := github.String(params.Comment)
×
UNCOV
198
                logger.Info().Msgf("dry run: create a PR comment on PR %d in repo %s/%s with the following body: %s",
×
199
                        params.Number, params.Owner, params.Repo, *body)
×
200
                return nil, nil
×
201
        case interfaces.ActionCmdOff:
×
UNCOV
202
                if params.Metadata == nil || params.Metadata.ReviewID == "" {
×
203
                        // We cannot do anything without the PR review ID, so we assume that turning the alert off is a success
×
204
                        return nil, fmt.Errorf("no PR comment ID provided: %w", enginerr.ErrActionTurnedOff)
×
205
                }
×
206
                logger.Info().Msgf("dry run: dismiss PR comment %s on PR %d in repo %s/%s", params.Metadata.ReviewID,
×
207
                        params.Number, params.Owner, params.Repo)
×
208
        case interfaces.ActionCmdDoNothing:
×
UNCOV
209
                // Return the previous alert status.
×
210
                return alert.runDoNothing(ctx, params)
×
211

212
        }
213
        return nil, enginerr.ErrActionSkipped
×
214
}
215

216
// runDoNothing returns the previous alert status
UNCOV
217
func (*Alert) runDoNothing(ctx context.Context, params *paramsPR) (json.RawMessage, error) {
×
UNCOV
218
        logger := zerolog.Ctx(ctx).With().Str("repo", params.Repo).Logger()
×
219

×
220
        logger.Debug().Msg("Running do nothing")
×
221

×
222
        // Return the previous alert status.
×
223
        err := enginerr.AlertStatusAsError(params.prevStatus)
×
224
        // If there is a valid alert metadata, return it too
×
225
        if params.prevStatus != nil {
×
226
                return params.prevStatus.AlertMetadata, err
×
227
        }
×
228
        // If there is no alert metadata, return nil as the metadata and the error
229
        return nil, err
×
230
}
231

232
// getParamsForPRComment extracts the details from the entity
233
func (alert *Alert) getParamsForPRComment(
234
        ctx context.Context,
235
        pr *pbinternal.PullRequest,
236
        params interfaces.ActionsParams,
237
        metadata *json.RawMessage,
238
) (*paramsPR, error) {
5✔
239
        logger := zerolog.Ctx(ctx)
5✔
240
        result := &paramsPR{
5✔
241
                prevStatus: params.GetEvalStatusFromDb(),
5✔
242
                Owner:      pr.GetRepoOwner(),
5✔
243
                Repo:       pr.GetRepoName(),
5✔
244
                CommitSha:  pr.GetCommitSha(),
5✔
245
        }
5✔
246

5✔
247
        // The GitHub Go API takes an int32, but our proto stores an int64; make sure we don't overflow
5✔
248
        // The PR number is an int in GitHub and Gitlab; in practice overflow will never happen.
5✔
249
        if pr.Number > math.MaxInt {
5✔
250
                return nil, fmt.Errorf("pr number is too large")
×
251
        }
×
252
        result.Number = int(pr.Number)
5✔
253

5✔
254
        commentTmpl, err := util.NewSafeHTMLTemplate(&alert.reviewCfg.ReviewMessage, "message")
5✔
255
        if err != nil {
5✔
UNCOV
256
                return nil, fmt.Errorf("cannot parse review message template: %w", err)
×
257
        }
×
258

259
        tmplParams := &PrCommentTemplateParams{
5✔
260
                EvalErrorDetails: enginerr.ErrorAsEvalDetails(params.GetEvalErr()),
5✔
261
        }
5✔
262

5✔
263
        if params.GetEvalResult() != nil {
10✔
264
                tmplParams.EvalResultOutput = params.GetEvalResult().Output
5✔
265
        }
5✔
266

267
        comment, err := commentTmpl.Render(ctx, tmplParams, PrCommentMaxLength)
5✔
268
        if err != nil {
5✔
269
                return nil, fmt.Errorf("cannot execute title template: %w", err)
×
270
        }
×
271

272
        result.Comment = comment
5✔
273

5✔
274
        // Unmarshal the existing alert metadata, if any
5✔
275
        if metadata != nil {
6✔
276
                meta := &alertMetadata{}
1✔
277
                err := json.Unmarshal(*metadata, meta)
1✔
278
                if err != nil {
1✔
UNCOV
279
                        // There's nothing saved apparently, so no need to fail here, but do log the error
×
UNCOV
280
                        logger.Debug().Msgf("error unmarshalling alert metadata: %v", err)
×
281
                } else {
1✔
282
                        result.Metadata = meta
1✔
283
                }
1✔
284
        }
285

286
        return result, nil
5✔
287
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc