| 28 | } |
| 29 | |
| 30 | func (g *GithubPRCommenter) Run(ctx context.Context, sharedState *types.AgentSharedState, params types.ActionParams) (types.ActionResult, error) { |
| 31 | result := struct { |
| 32 | Repository string `json:"repository"` |
| 33 | Owner string `json:"owner"` |
| 34 | PRNumber int `json:"pr_number"` |
| 35 | Comment string `json:"comment"` |
| 36 | }{} |
| 37 | err := params.Unmarshal(&result) |
| 38 | if err != nil { |
| 39 | return types.ActionResult{}, fmt.Errorf("failed to unmarshal params: %w", err) |
| 40 | } |
| 41 | |
| 42 | if g.repository != "" && g.owner != "" { |
| 43 | result.Repository = g.repository |
| 44 | result.Owner = g.owner |
| 45 | } |
| 46 | |
| 47 | // First verify the PR exists and is in a valid state |
| 48 | pr, _, err := g.client.PullRequests.Get(ctx, result.Owner, result.Repository, result.PRNumber) |
| 49 | if err != nil { |
| 50 | return types.ActionResult{}, fmt.Errorf("failed to fetch PR #%d: %w", result.PRNumber, err) |
| 51 | } |
| 52 | if pr == nil { |
| 53 | return types.ActionResult{Result: fmt.Sprintf("Pull request #%d not found in repository %s/%s", result.PRNumber, result.Owner, result.Repository)}, nil |
| 54 | } |
| 55 | |
| 56 | // Check if PR is in a state that allows comments |
| 57 | if *pr.State != "open" { |
| 58 | return types.ActionResult{Result: fmt.Sprintf("Pull request #%d is not open (current state: %s)", result.PRNumber, *pr.State)}, nil |
| 59 | } |
| 60 | |
| 61 | if result.Comment == "" { |
| 62 | return types.ActionResult{Result: "No comment provided"}, nil |
| 63 | } |
| 64 | |
| 65 | // Try both PullRequests and Issues API for general comments |
| 66 | var resp *github.Response |
| 67 | |
| 68 | // First try PullRequests API |
| 69 | _, resp, err = g.client.PullRequests.CreateComment(ctx, result.Owner, result.Repository, result.PRNumber, &github.PullRequestComment{ |
| 70 | Body: &result.Comment, |
| 71 | }) |
| 72 | |
| 73 | // If that fails with 403, try Issues API |
| 74 | if err != nil && resp != nil && resp.StatusCode == 403 { |
| 75 | _, resp, err = g.client.Issues.CreateComment(ctx, result.Owner, result.Repository, result.PRNumber, &github.IssueComment{ |
| 76 | Body: &result.Comment, |
| 77 | }) |
| 78 | } |
| 79 | |
| 80 | if err != nil { |
| 81 | return types.ActionResult{Result: fmt.Sprintf("Error adding general comment: %s", err.Error())}, nil |
| 82 | } |
| 83 | |
| 84 | return types.ActionResult{ |
| 85 | Result: "Successfully added general comment to pull request", |
| 86 | }, nil |
| 87 | } |