From 6d082367738e775e286e531f98ef39fa21f37346 Mon Sep 17 00:00:00 2001 From: claw Date: Wed, 13 May 2026 13:35:58 -0700 Subject: [PATCH] feat(vcs): add CommitID to ReviewRequest (#115) Add CommitID string field to vcs.ReviewRequest so both platform adapters can thread the commit anchor through the abstraction layer. Changes: - vcs/types.go: Add CommitID field with json tag commit_id,omitempty - gitea/client.go: Re-add commitID parameter to PostReview (was removed during PR #112 refactoring) - gitea/adapter.go: Forward req.CommitID to underlying client - github/review.go: Use req.CommitID as primary anchor, fall back to comment-derived CommitID when empty, reject on conflict - cmd/review-bot/main.go: Set ReviewRequest.CommitID = evaluatedSHA Fixes #115 --- cmd/review-bot/main.go | 1 + gitea/adapter.go | 2 +- gitea/adapter_test.go | 34 ++++++++ gitea/client.go | 8 +- gitea/client_test.go | 65 ++++++++++++++- gitea/post_review_comments_test.go | 4 +- github/review.go | 15 ++-- github/review_test.go | 122 +++++++++++++++++++++++++++++ vcs/types.go | 5 ++ 9 files changed, 243 insertions(+), 13 deletions(-) diff --git a/cmd/review-bot/main.go b/cmd/review-bot/main.go index d84afb3..2063a64 100644 --- a/cmd/review-bot/main.go +++ b/cmd/review-bot/main.go @@ -485,6 +485,7 @@ func main() { reviewReq := vcs.ReviewRequest{ Body: reviewBody, Event: event, + CommitID: evaluatedSHA, Comments: inlineComments, } posted, err := client.PostReview(ctx, owner, repoName, prNumber, reviewReq) diff --git a/gitea/adapter.go b/gitea/adapter.go index 176c722..5d13d8b 100644 --- a/gitea/adapter.go +++ b/gitea/adapter.go @@ -181,7 +181,7 @@ func (a *Adapter) PostReview(ctx context.Context, owner, repo string, number int } } - review, err := a.client.PostReview(ctx, owner, repo, number, event, req.Body, giteaComments) + review, err := a.client.PostReview(ctx, owner, repo, number, event, req.Body, req.CommitID, giteaComments) if err != nil { return nil, fmt.Errorf("post review: %w", err) } diff --git a/gitea/adapter_test.go b/gitea/adapter_test.go index a4aea9d..a695233 100644 --- a/gitea/adapter_test.go +++ b/gitea/adapter_test.go @@ -214,6 +214,40 @@ func TestAdapter_PostReview_EventTranslation(t *testing.T) { } } + +func TestAdapter_PostReview_CommitID(t *testing.T) { + var gotCommitID string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var payload struct { + CommitID string `json:"commit_id"` + } + json.NewDecoder(r.Body).Decode(&payload) + gotCommitID = payload.CommitID + json.NewEncoder(w).Encode(map[string]any{ + "id": 1, + "body": "test", + "user": map[string]any{"login": "bot"}, + "commit_id": payload.CommitID, + }) + })) + defer server.Close() + + client := gitea.NewClient(server.URL, "token") + adapter := gitea.NewAdapter(client) + + _, err := adapter.PostReview(context.Background(), "owner", "repo", 1, vcs.ReviewRequest{ + Body: "test", + Event: vcs.ReviewEventApprove, + CommitID: "sha256abc", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if gotCommitID != "sha256abc" { + t.Errorf("expected commit_id %q forwarded to client, got %q", "sha256abc", gotCommitID) + } +} func TestAdapter_PostReview_WithComments_PositionTranslation(t *testing.T) { diff := `diff --git a/main.go b/main.go --- a/main.go diff --git a/gitea/client.go b/gitea/client.go index 2fec35d..64447b4 100644 --- a/gitea/client.go +++ b/gitea/client.go @@ -186,18 +186,22 @@ func (c *Client) GetFileContentRef(ctx context.Context, owner, repo, filepath, r } // PostReview submits a review to a PR and returns the created review. -// event should be "APPROVED" or "REQUEST_CHANGES". +// event should be one of "APPROVED", "REQUEST_CHANGES", or "COMMENT". +// commitID anchors the review to a specific commit SHA. If empty, Gitea +// defaults to the current PR head. // comments are optional inline comments attached to specific lines. -func (c *Client) PostReview(ctx context.Context, owner, repo string, number int, event, body string, comments []ReviewComment) (*Review, error) { +func (c *Client) PostReview(ctx context.Context, owner, repo string, number int, event, body, commitID string, comments []ReviewComment) (*Review, error) { reqURL := fmt.Sprintf("%s/api/v1/repos/%s/%s/pulls/%d/reviews", c.baseURL, url.PathEscape(owner), url.PathEscape(repo), number) payload := struct { Body string `json:"body"` Event string `json:"event"` + CommitID string `json:"commit_id,omitempty"` Comments []ReviewComment `json:"comments,omitempty"` }{ Body: body, Event: event, + CommitID: commitID, Comments: comments, } diff --git a/gitea/client_test.go b/gitea/client_test.go index 2637c2e..8525a72 100644 --- a/gitea/client_test.go +++ b/gitea/client_test.go @@ -135,7 +135,7 @@ func TestPostReview(t *testing.T) { defer server.Close() client := NewClient(server.URL, "test-token") - review, err := client.PostReview(context.Background(), "owner", "repo", 3, "APPROVED", "LGTM", nil) + review, err := client.PostReview(context.Background(), "owner", "repo", 3, "APPROVED", "LGTM", "", nil) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -147,6 +147,67 @@ func TestPostReview(t *testing.T) { } } +func TestPostReview_CommitID(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Fatalf("expected POST, got %s", r.Method) + } + + body, _ := io.ReadAll(r.Body) + var payload struct { + Body string `json:"body"` + Event string `json:"event"` + CommitID string `json:"commit_id"` + } + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatalf("unmarshal payload: %v", err) + } + if payload.CommitID != "deadbeef123" { + t.Errorf("expected commit_id %q, got %q", "deadbeef123", payload.CommitID) + } + if payload.Event != "APPROVED" { + t.Errorf("expected event APPROVED, got %q", payload.Event) + } + + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"id":101,"user":{"login":"review-bot"},"state":"APPROVED","stale":false,"commit_id":"deadbeef123"}`)) + })) + defer server.Close() + + client := NewClient(server.URL, "test-token") + review, err := client.PostReview(context.Background(), "owner", "repo", 3, "APPROVED", "LGTM", "deadbeef123", nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if review.ID != 101 { + t.Errorf("expected review ID 101, got %d", review.ID) + } + if review.CommitID != "deadbeef123" { + t.Errorf("expected commit_id %q, got %q", "deadbeef123", review.CommitID) + } +} + +func TestPostReview_EmptyCommitID_OmittedFromPayload(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + // When commit_id is empty, it should not appear in JSON (omitempty) + if strings.Contains(string(body), "commit_id") { + t.Errorf("expected commit_id to be omitted from payload, got: %s", body) + } + + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"id":102,"user":{"login":"review-bot"},"state":"APPROVED","stale":false}`)) + })) + defer server.Close() + + client := NewClient(server.URL, "test-token") + _, err := client.PostReview(context.Background(), "owner", "repo", 3, "APPROVED", "LGTM", "", nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + + func TestGetPullRequest_Non200(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) @@ -182,7 +243,7 @@ func TestPostReview_Non200(t *testing.T) { defer server.Close() client := NewClient(server.URL, "test-token") - _, err := client.PostReview(context.Background(), "owner", "repo", 1, "APPROVED", "test", nil) + _, err := client.PostReview(context.Background(), "owner", "repo", 1, "APPROVED", "test", "", nil) if err == nil { t.Fatal("expected error for 403, got nil") } diff --git a/gitea/post_review_comments_test.go b/gitea/post_review_comments_test.go index e58d05d..5090a21 100644 --- a/gitea/post_review_comments_test.go +++ b/gitea/post_review_comments_test.go @@ -37,7 +37,7 @@ func TestPostReview_WithComments(t *testing.T) { {Path: "util.go", NewPosition: 10, Body: "[MINOR] Style issue"}, } - _, err := client.PostReview(context.Background(), "owner", "repo", 1, "REQUEST_CHANGES", "summary", comments) + _, err := client.PostReview(context.Background(), "owner", "repo", 1, "REQUEST_CHANGES", "summary", "abc123", comments) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -72,7 +72,7 @@ func TestPostReview_NilComments(t *testing.T) { defer server.Close() client := NewClient(server.URL, "test-token") - _, err := client.PostReview(context.Background(), "owner", "repo", 1, "APPROVED", "all good", nil) + _, err := client.PostReview(context.Background(), "owner", "repo", 1, "APPROVED", "all good", "", nil) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/github/review.go b/github/review.go index 467f890..d6e8243 100644 --- a/github/review.go +++ b/github/review.go @@ -82,21 +82,24 @@ func translateGitHubReviewState(state string) string { // (via the omitempty tag on postReviewRequest.Comments). // // The GitHub API accepts a single commit_id per review submission. PostReview -// extracts it from the first comment with a non-empty CommitID. If any subsequent -// comment specifies a different CommitID, PostReview returns ErrConflictingCommitIDs. +// uses req.CommitID as the primary anchor when set. If req.CommitID is empty, +// it falls back to extracting commit_id from the first comment with a non-empty +// CommitID. If any comment specifies a CommitID that conflicts with the +// resolved value, PostReview returns ErrConflictingCommitIDs. // Comments with an empty CommitID are allowed and inherit the review-level value. func (c *Client) PostReview(ctx context.Context, owner, repo string, number int, req vcs.ReviewRequest) (*vcs.Review, error) { reqURL := fmt.Sprintf("%s/repos/%s/%s/pulls/%d/reviews", c.baseURL, url.PathEscape(owner), url.PathEscape(repo), number) payload := postReviewRequest{ - Body: req.Body, - Event: string(req.Event), + CommitID: req.CommitID, + Body: req.Body, + Event: string(req.Event), } // Build the payload in one pass. The GitHub API accepts a single commit_id - // per review; we extract it from the first comment that supplies one and - // reject the request if any other comment disagrees. + // per review. We use req.CommitID as the primary anchor; if any comment + // specifies a different non-empty CommitID, we reject the request. for _, comment := range req.Comments { if comment.CommitID != "" { if payload.CommitID == "" { diff --git a/github/review_test.go b/github/review_test.go index da17d8e..4627f5a 100644 --- a/github/review_test.go +++ b/github/review_test.go @@ -389,3 +389,125 @@ func TestPostReview_ConflictingCommitIDs(t *testing.T) { t.Errorf("expected ErrConflictingCommitIDs, got: %v", err) } } + +func TestPostReview_CommitIDFromRequest(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var req postReviewRequest + if err := json.Unmarshal(body, &req); err != nil { + t.Fatalf("unmarshal request: %v", err) + } + if req.CommitID != "req-level-sha" { + t.Errorf("expected commit_id %q, got %q", "req-level-sha", req.CommitID) + } + + json.NewEncoder(w).Encode(map[string]interface{}{ + "id": 200, + "body": "ok", + "state": "APPROVED", + "commit_id": "req-level-sha", + "user": map[string]string{"login": "bot"}, + }) + }) + + // CommitID set at request level, no comments + review, err := c.PostReview(context.Background(), "owner", "repo", 5, vcs.ReviewRequest{ + Body: "ok", + Event: vcs.ReviewEventApprove, + CommitID: "req-level-sha", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if review.CommitID != "req-level-sha" { + t.Errorf("expected commit_id %q, got %q", "req-level-sha", review.CommitID) + } +} + +func TestPostReview_CommitIDFallbackToComment(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var req postReviewRequest + if err := json.Unmarshal(body, &req); err != nil { + t.Fatalf("unmarshal request: %v", err) + } + // When req.CommitID is empty, should fall back to comment's CommitID + if req.CommitID != "comment-sha" { + t.Errorf("expected commit_id %q (from comment fallback), got %q", "comment-sha", req.CommitID) + } + + json.NewEncoder(w).Encode(map[string]interface{}{ + "id": 201, + "body": "ok", + "state": "APPROVED", + "commit_id": "comment-sha", + "user": map[string]string{"login": "bot"}, + }) + }) + + review, err := c.PostReview(context.Background(), "owner", "repo", 5, vcs.ReviewRequest{ + Body: "ok", + Event: vcs.ReviewEventApprove, + // CommitID intentionally empty — should fall back to comment + Comments: []vcs.ReviewComment{ + {Path: "main.go", Position: 1, CommitID: "comment-sha", Body: "nit"}, + }, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if review.CommitID != "comment-sha" { + t.Errorf("expected commit_id %q, got %q", "comment-sha", review.CommitID) + } +} + +func TestPostReview_CommitIDConflictBetweenRequestAndComment(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + t.Fatal("request should not have been sent") + }) + + _, err := c.PostReview(context.Background(), "owner", "repo", 5, vcs.ReviewRequest{ + Body: "ok", + Event: vcs.ReviewEventApprove, + CommitID: "req-sha", + Comments: []vcs.ReviewComment{ + {Path: "main.go", Position: 1, CommitID: "different-sha", Body: "nit"}, + }, + }) + if !errors.Is(err, ErrConflictingCommitIDs) { + t.Errorf("expected ErrConflictingCommitIDs, got %v", err) + } +} + +func TestPostReview_CommitIDMatchBetweenRequestAndComment(t *testing.T) { + c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var req postReviewRequest + if err := json.Unmarshal(body, &req); err != nil { + t.Fatalf("unmarshal request: %v", err) + } + if req.CommitID != "same-sha" { + t.Errorf("expected commit_id %q, got %q", "same-sha", req.CommitID) + } + + json.NewEncoder(w).Encode(map[string]interface{}{ + "id": 202, + "body": "ok", + "state": "APPROVED", + "commit_id": "same-sha", + "user": map[string]string{"login": "bot"}, + }) + }) + + _, err := c.PostReview(context.Background(), "owner", "repo", 5, vcs.ReviewRequest{ + Body: "ok", + Event: vcs.ReviewEventApprove, + CommitID: "same-sha", + Comments: []vcs.ReviewComment{ + {Path: "main.go", Position: 1, CommitID: "same-sha", Body: "nit"}, + }, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } +} diff --git a/vcs/types.go b/vcs/types.go index 608ad27..5f5a5e1 100644 --- a/vcs/types.go +++ b/vcs/types.go @@ -94,5 +94,10 @@ type ReviewRequest struct { Body string `json:"body"` // Event is the review action (approve, request changes, or comment). Event ReviewEvent `json:"event"` + // CommitID anchors the review to a specific commit SHA. + // Both GitHub and Gitea accept this at the review level. + // If empty, each platform applies its default behavior (Gitea uses PR + // head; GitHub derives from comments or omits). + CommitID string `json:"commit_id,omitempty"` Comments []ReviewComment `json:"comments,omitempty"` }