c11a6bbfd2
* feat(github): add issue watcher with task creation and auto-cleanup
Add a GitHub Issue Watcher feature that polls for new issues matching
configurable filters and automatically creates tasks for them. This
complements the existing PR Review Watcher with the same patterns.
Backend:
- Issue watch CRUD (models, store, service, controller, WS handlers)
- Poller integration with configurable intervals
- Event-driven task creation via orchestrator
- Repository resolution and worktree support for issue tasks
- Auto-cleanup of tasks for closed issues (CleanupClosedIssueTasks)
- GetIssueState client method across all implementations
- Default branch auto-detection from cloned repo HEAD
Frontend:
- Issue watch settings UI (table, dialog, placeholders)
- Issue link icon on task cards (green circle-dot)
- API client, store slice, and hook for issue watches
- SSR and WS hydration of issue metadata
* fix: resolve golangci-lint errors (goconst, nestif, dupl) and prettier formatting
* fix(github): fix issue watch update shape, trigger key, and label quoting
- httpUpdateIssueWatch now returns the full IssueWatch object instead of
{updated:true} so the frontend store correctly refreshes after edits
- httpTriggerIssueWatch returns new_issues_found to match TriggerIssueResponse
type; was returning new_issues so the toast count was always 0
- buildIssueFilter uses conditional quoting instead of fmt.Sprintf %q to
avoid Go escape sequences in GitHub search qualifiers
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* fix: resolve eslint warnings (max-lines-per-function, no-nested-ternary)
* test(github): add issue watcher tests and fix review feedback
- Add TestInterpolateIssuePrompt (4 cases: empty/all/none/partial)
- Add TestCreateIssueTask (3 cases: skip/reserve+assign/release on fail)
- Add TestShouldDeleteIssueTask (4 cases: open/closed+sessions/closed/error)
- Fix WS response key new_issues -> new_issues_found
- Fix fmt.Printf -> fmt.Fprintf(os.Stderr) in store.go
- Add CleanupClosedIssueTasks call in WS trigger handler
* fix: address PR review feedback and CI failures
- Split test files to fix revive file-length-limit (service_test.go,
event_handlers_github_test.go)
- Add session checker guard in CleanupClosedIssueTasks
- Normalize poll intervals on UpdateIssueWatch
- Add cleanup call in TriggerAllIssueChecks loop
- Log cleanup errors in controller and WS handler
- Prefer refs/remotes/origin/HEAD in detectGitDefaultBranch
- Add aria-label to issue task icon
- Fix TypeScript type errors: add linkedIssues to GitHubSlice,
fix hook exports, remove invalid imports
* fix: split test files exceeding revive limit and clean up minor issues
- Split service_test.go (883→779 lines): move TestTriggerPRSync_* to
service_pr_sync_test.go
- Split event_handlers_github_test.go (806→677 lines): move
TestCreateReviewTask_* and helpers to event_handlers_github_review_test.go
- Remove redundant s.taskSessionChecker nil-check inside shouldDeleteIssueTask
(early guard at CleanupClosedIssueTasks already ensures it is non-nil)
- Remove unreachable dead guard in detectAndPersistDefaultBranch
(repo.DefaultBranch is always "" at that call site)
- Fix bogus #0 issue badge in task-session-sidebar.tsx when issueNumber is absent
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* fix: address Claude review — poll clamp and prompt injection
- Handle v <= 0 in UpdateIssueWatch poll interval (fall back to default)
- Remove {{issue.body}} from default template to prevent prompt injection
- Update test expected output for new default template
* fix: remove {{issue.body}} from frontend DEFAULT_ISSUE_WATCH_PROMPT
Mirrors the backend fix — the UI pre-fills the prompt so the backend
fallback was never reached. The placeholder stays in
ISSUE_WATCH_PLACEHOLDERS for explicit opt-in.
* feat(github): add isIssueWatch sidebar filter dimension
Add isIssueWatch boolean to KanbanState, TaskSwitcherItem, and sidebar
filter registry — mirroring the isPRReview pattern. Issue-watch tasks
(created from issue_watch_id in metadata) can now be explicitly filtered
in the sidebar, just like PR review tasks.
Files changed:
- sidebar-view-types: add isIssueWatch dimension
- filter-dimension-registry: add Issue watch filter meta
- apply-view: add isIssueWatch extractor
- kanban types: add isIssueWatch field
- TaskSwitcherItem: add isIssueWatch field
- use-all-workflow-snapshots: derive isIssueWatch from metadata
- ssr/mapper: derive isIssueWatch from metadata
- task-session-sidebar: pass isIssueWatch, extract helpers to fix complexity
* fix: correct deleteIssueWatch response type to match backend
Backend httpDeleteIssueWatch returns {"deleted": true}; the frontend
type was { success: boolean } — a mismatch with no functional impact
(return value is ignored) but wrong per TypeScript contract.
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* refactor: extract metadata helpers to shared lib/metadata-utils.ts
- Move isPRReviewFromMetadata, isIssueWatchFromMetadata, and
issueFieldsFromMetadata to a shared module to eliminate duplicate
definitions (sonarjs/no-identical-functions).
- Fix deleteIssueWatch response type: { success: boolean } -> { deleted: boolean }
to match the actual backend response.
* style: fix prettier formatting
* test(web): add tests for isIssueWatch filter dimension and metadata-utils
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* style: fix prettier formatting in test files
* fix(github): cascade-delete issue watch tasks on watch deletion and add isPRReview to SSR mapper
- DeleteIssueWatch now wraps in a transaction and deletes related
github_issue_watch_tasks rows before removing the watch; prevents
orphaned dedup rows accumulating after a watch is deleted
- snapshotToState in mapper.ts now also sets isPRReview from metadata,
matching the mapping already done in use-all-workflow-snapshots.ts
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* style: extract duplicate string constant in metadata-utils test
* style: extract repeated WS error strings into constants in handlers.go
goconst min-occurrences: 3 — 'invalid payload' (6x) and 'id required' (4x)
both exceed the threshold. Extract to package-level constants.
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* style: extract repeated issue key strings into constants in event_handlers_github.go
goconst min-occurrences: 3 — 'issue_number' (9x) and 'issue_watch_id' (5x)
both newly introduced in this PR exceed the threshold.
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* style: fix prettier formatting in metadata-utils test
---------
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
537 lines
16 KiB
Go
537 lines
16 KiB
Go
package github
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
githubAPIBase = "https://api.github.com"
|
|
githubAccept = "application/vnd.github+json"
|
|
githubAPIVersion = "2022-11-28"
|
|
)
|
|
|
|
// GitHubAPIError represents an error response from the GitHub API with a status code.
|
|
type GitHubAPIError struct {
|
|
StatusCode int
|
|
Endpoint string
|
|
Body string
|
|
}
|
|
|
|
func (e *GitHubAPIError) Error() string {
|
|
return fmt.Sprintf("GitHub API %s returned %d: %s", e.Endpoint, e.StatusCode, e.Body)
|
|
}
|
|
|
|
// PATClient implements Client using a GitHub Personal Access Token.
|
|
type PATClient struct {
|
|
token string
|
|
httpClient *http.Client
|
|
username string // cached after first GetAuthenticatedUser call
|
|
}
|
|
|
|
// NewPATClient creates a new PAT-based GitHub client.
|
|
func NewPATClient(token string) *PATClient {
|
|
return &PATClient{
|
|
token: token,
|
|
httpClient: &http.Client{
|
|
Timeout: 30 * time.Second,
|
|
},
|
|
}
|
|
}
|
|
|
|
// setGitHubHeaders sets the common Authorization, Accept, and API version headers.
|
|
func (c *PATClient) setGitHubHeaders(req *http.Request) {
|
|
req.Header.Set("Authorization", "token "+c.token)
|
|
req.Header.Set("Accept", githubAccept)
|
|
req.Header.Set("X-GitHub-Api-Version", githubAPIVersion)
|
|
}
|
|
|
|
func (c *PATClient) IsAuthenticated(ctx context.Context) (bool, error) {
|
|
_, err := c.GetAuthenticatedUser(ctx)
|
|
return err == nil, nil
|
|
}
|
|
|
|
func (c *PATClient) GetAuthenticatedUser(ctx context.Context) (string, error) {
|
|
if c.username != "" {
|
|
return c.username, nil
|
|
}
|
|
var user struct {
|
|
Login string `json:"login"`
|
|
}
|
|
if err := c.get(ctx, "/user", &user); err != nil {
|
|
return "", err
|
|
}
|
|
c.username = user.Login
|
|
return c.username, nil
|
|
}
|
|
|
|
func (c *PATClient) GetPR(ctx context.Context, owner, repo string, number int) (*PR, error) {
|
|
var raw patPR
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, number)
|
|
if err := c.get(ctx, endpoint, &raw); err != nil {
|
|
return nil, fmt.Errorf("get PR #%d: %w", number, err)
|
|
}
|
|
return convertPatPR(&raw, owner, repo), nil
|
|
}
|
|
|
|
func (c *PATClient) FindPRByBranch(ctx context.Context, owner, repo, branch string) (*PR, error) {
|
|
var raw []patPR
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/pulls?head=%s:%s&state=open&per_page=1",
|
|
owner, repo, owner, branch)
|
|
if err := c.get(ctx, endpoint, &raw); err != nil {
|
|
return nil, fmt.Errorf("find PR by branch: %w", err)
|
|
}
|
|
if len(raw) == 0 {
|
|
return nil, nil
|
|
}
|
|
return convertPatPR(&raw[0], owner, repo), nil
|
|
}
|
|
|
|
func (c *PATClient) ListAuthoredPRs(ctx context.Context, owner, repo string) ([]*PR, error) {
|
|
user, err := c.GetAuthenticatedUser(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var raw []patPR
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/pulls?state=open&per_page=100", owner, repo)
|
|
if err := c.get(ctx, endpoint, &raw); err != nil {
|
|
return nil, fmt.Errorf("list PRs: %w", err)
|
|
}
|
|
var result []*PR
|
|
for i := range raw {
|
|
if raw[i].User.Login == user {
|
|
result = append(result, convertPatPR(&raw[i], owner, repo))
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (c *PATClient) ListReviewRequestedPRs(ctx context.Context, scope, filter, customQuery string) ([]*PR, error) {
|
|
query := buildReviewSearchQuery(scope, filter, customQuery)
|
|
var result struct {
|
|
Items []patSearchItem `json:"items"`
|
|
}
|
|
endpoint := "/search/issues?q=" + url.QueryEscape(query) + "&per_page=50"
|
|
if err := c.get(ctx, endpoint, &result); err != nil {
|
|
return nil, fmt.Errorf("search review-requested: %w", err)
|
|
}
|
|
prs := make([]*PR, len(result.Items))
|
|
for i, item := range result.Items {
|
|
prs[i] = convertSearchItemToPR(
|
|
item.Number, item.Title, item.HTMLURL, item.State,
|
|
item.User.Login, item.RepositoryURL, item.Draft,
|
|
item.CreatedAt, item.UpdatedAt,
|
|
)
|
|
}
|
|
return prs, nil
|
|
}
|
|
|
|
func (c *PATClient) ListIssues(ctx context.Context, filter, customQuery string) ([]*Issue, error) {
|
|
query := buildIssueSearchQuery(filter, customQuery)
|
|
var result struct {
|
|
Items []issueSearchItem `json:"items"`
|
|
}
|
|
endpoint := "/search/issues?q=" + url.QueryEscape(query) + "&per_page=50"
|
|
if err := c.get(ctx, endpoint, &result); err != nil {
|
|
return nil, fmt.Errorf("search issues: %w", err)
|
|
}
|
|
return parseIssueSearchResults(result.Items), nil
|
|
}
|
|
|
|
func (c *PATClient) GetIssueState(ctx context.Context, owner, repo string, number int) (string, error) {
|
|
var result struct {
|
|
State string `json:"state"`
|
|
}
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, number)
|
|
if err := c.get(ctx, endpoint, &result); err != nil {
|
|
return "", fmt.Errorf("get issue state: %w", err)
|
|
}
|
|
return result.State, nil
|
|
}
|
|
|
|
func (c *PATClient) ListUserOrgs(ctx context.Context) ([]GitHubOrg, error) {
|
|
var raw []struct {
|
|
Login string `json:"login"`
|
|
AvatarURL string `json:"avatar_url"`
|
|
}
|
|
if err := c.get(ctx, "/user/orgs?per_page=100", &raw); err != nil {
|
|
return nil, fmt.Errorf("list user orgs: %w", err)
|
|
}
|
|
orgs := make([]GitHubOrg, len(raw))
|
|
for i, r := range raw {
|
|
orgs[i] = GitHubOrg{Login: r.Login, AvatarURL: r.AvatarURL}
|
|
}
|
|
return orgs, nil
|
|
}
|
|
|
|
func (c *PATClient) SearchOrgRepos(ctx context.Context, org, query string, limit int) ([]GitHubRepo, error) {
|
|
q := "org:" + org
|
|
if query != "" {
|
|
q += " " + query
|
|
}
|
|
if limit <= 0 {
|
|
limit = 20
|
|
}
|
|
var result struct {
|
|
Items []struct {
|
|
FullName string `json:"full_name"`
|
|
Owner struct {
|
|
Login string `json:"login"`
|
|
} `json:"owner"`
|
|
Name string `json:"name"`
|
|
Private bool `json:"private"`
|
|
} `json:"items"`
|
|
}
|
|
endpoint := fmt.Sprintf("/search/repositories?q=%s&per_page=%d", url.QueryEscape(q), limit)
|
|
if err := c.get(ctx, endpoint, &result); err != nil {
|
|
return nil, fmt.Errorf("search org repos: %w", err)
|
|
}
|
|
repos := make([]GitHubRepo, len(result.Items))
|
|
for i, item := range result.Items {
|
|
repos[i] = GitHubRepo{
|
|
FullName: item.FullName,
|
|
Owner: item.Owner.Login,
|
|
Name: item.Name,
|
|
Private: item.Private,
|
|
}
|
|
}
|
|
return repos, nil
|
|
}
|
|
|
|
func (c *PATClient) ListPRReviews(ctx context.Context, owner, repo string, number int) ([]PRReview, error) {
|
|
var raw []struct {
|
|
ID int64 `json:"id"`
|
|
State string `json:"state"`
|
|
Body string `json:"body"`
|
|
SubmittedAt time.Time `json:"submitted_at"`
|
|
User struct {
|
|
Login string `json:"login"`
|
|
AvatarURL string `json:"avatar_url"`
|
|
} `json:"user"`
|
|
}
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, number)
|
|
if err := c.get(ctx, endpoint, &raw); err != nil {
|
|
return nil, err
|
|
}
|
|
reviews := make([]PRReview, len(raw))
|
|
for i, r := range raw {
|
|
reviews[i] = PRReview{
|
|
ID: r.ID,
|
|
Author: r.User.Login,
|
|
AuthorAvatar: r.User.AvatarURL,
|
|
State: r.State,
|
|
Body: r.Body,
|
|
CreatedAt: r.SubmittedAt,
|
|
}
|
|
}
|
|
return reviews, nil
|
|
}
|
|
|
|
func (c *PATClient) ListPRComments(ctx context.Context, owner, repo string, number int, since *time.Time) ([]PRComment, error) {
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/comments?per_page=100", owner, repo, number)
|
|
if since != nil {
|
|
endpoint += "&since=" + url.QueryEscape(since.Format(time.RFC3339))
|
|
}
|
|
var reviewRaw []ghComment
|
|
if err := c.get(ctx, endpoint, &reviewRaw); err != nil {
|
|
return nil, err
|
|
}
|
|
issueEndpoint := fmt.Sprintf("/repos/%s/%s/issues/%d/comments?per_page=100", owner, repo, number)
|
|
if since != nil {
|
|
issueEndpoint += "&since=" + url.QueryEscape(since.Format(time.RFC3339))
|
|
}
|
|
var issueRaw []ghIssueComment
|
|
if err := c.get(ctx, issueEndpoint, &issueRaw); err != nil {
|
|
return nil, err
|
|
}
|
|
return mergeAndSortPRComments(convertRawComments(reviewRaw), convertRawIssueComments(issueRaw)), nil
|
|
}
|
|
|
|
func (c *PATClient) ListCheckRuns(ctx context.Context, owner, repo, ref string) ([]CheckRun, error) {
|
|
var checkRunsResult struct {
|
|
CheckRuns []ghCheckRun `json:"check_runs"`
|
|
}
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/commits/%s/check-runs", owner, repo, ref)
|
|
if err := c.get(ctx, endpoint, &checkRunsResult); err != nil {
|
|
return nil, err
|
|
}
|
|
var statusResult struct {
|
|
Statuses []ghStatusContext `json:"statuses"`
|
|
}
|
|
statusEndpoint := fmt.Sprintf("/repos/%s/%s/commits/%s/status", owner, repo, ref)
|
|
if err := c.get(ctx, statusEndpoint, &statusResult); err != nil {
|
|
return nil, err
|
|
}
|
|
return mergeChecks(
|
|
convertRawCheckRuns(checkRunsResult.CheckRuns),
|
|
convertRawStatusContexts(statusResult.Statuses),
|
|
), nil
|
|
}
|
|
|
|
func (c *PATClient) GetPRFeedback(ctx context.Context, owner, repo string, number int) (*PRFeedback, error) {
|
|
return getPRFeedback(ctx, c, owner, repo, number)
|
|
}
|
|
|
|
func (c *PATClient) GetPRStatus(ctx context.Context, owner, repo string, number int) (*PRStatus, error) {
|
|
return getPRStatus(ctx, c, owner, repo, number)
|
|
}
|
|
|
|
func (c *PATClient) ListPRFiles(ctx context.Context, owner, repo string, number int) ([]PRFile, error) {
|
|
var raw []ghPRFile
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/files?per_page=100", owner, repo, number)
|
|
if err := c.get(ctx, endpoint, &raw); err != nil {
|
|
return nil, fmt.Errorf("list PR files: %w", err)
|
|
}
|
|
return convertRawPRFiles(raw), nil
|
|
}
|
|
|
|
func (c *PATClient) ListPRCommits(ctx context.Context, owner, repo string, number int) ([]PRCommitInfo, error) {
|
|
var raw []ghPRCommit
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/commits?per_page=100", owner, repo, number)
|
|
if err := c.get(ctx, endpoint, &raw); err != nil {
|
|
return nil, fmt.Errorf("list PR commits: %w", err)
|
|
}
|
|
return convertRawPRCommits(raw), nil
|
|
}
|
|
|
|
func (c *PATClient) ListRepoBranches(ctx context.Context, owner, repo string) ([]RepoBranch, error) {
|
|
var branches []RepoBranch
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/branches?per_page=100", owner, repo)
|
|
for endpoint != "" {
|
|
var page []struct {
|
|
Name string `json:"name"`
|
|
}
|
|
nextLink, err := c.getPaginated(ctx, endpoint, &page)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list repo branches: %w", err)
|
|
}
|
|
for _, b := range page {
|
|
branches = append(branches, RepoBranch{Name: b.Name})
|
|
}
|
|
endpoint = nextLink
|
|
}
|
|
return branches, nil
|
|
}
|
|
|
|
func (c *PATClient) SubmitReview(ctx context.Context, owner, repo string, number int, event, body string) error {
|
|
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, number)
|
|
payload := map[string]string{"event": event}
|
|
if body != "" {
|
|
payload["body"] = body
|
|
}
|
|
jsonBody, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return fmt.Errorf("marshal review payload: %w", err)
|
|
}
|
|
return c.post(ctx, endpoint, jsonBody)
|
|
}
|
|
|
|
func (c *PATClient) post(ctx context.Context, endpoint string, body []byte) error {
|
|
u := githubAPIBase + endpoint
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.setGitHubHeaders(req)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := c.httpClient.Do(req)
|
|
if err != nil {
|
|
return fmt.Errorf("request POST %s: %w", endpoint, err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
if resp.StatusCode >= 400 {
|
|
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
return fmt.Errorf("GitHub API POST %s returned %d: %s", endpoint, resp.StatusCode, string(respBody))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *PATClient) get(ctx context.Context, endpoint string, result interface{}) error {
|
|
url := githubAPIBase + endpoint
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.setGitHubHeaders(req)
|
|
|
|
resp, err := c.httpClient.Do(req)
|
|
if err != nil {
|
|
return fmt.Errorf("request %s: %w", endpoint, err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
if resp.StatusCode >= 400 {
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
return &GitHubAPIError{StatusCode: resp.StatusCode, Endpoint: endpoint, Body: string(body)}
|
|
}
|
|
return json.NewDecoder(resp.Body).Decode(result)
|
|
}
|
|
|
|
// getPaginated is like get but also returns the "next" link from the Link header, if any.
|
|
func (c *PATClient) getPaginated(ctx context.Context, endpoint string, result interface{}) (string, error) {
|
|
u := githubAPIBase + endpoint
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
c.setGitHubHeaders(req)
|
|
|
|
resp, err := c.httpClient.Do(req)
|
|
if err != nil {
|
|
return "", fmt.Errorf("request %s: %w", endpoint, err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
if resp.StatusCode >= 400 {
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
return "", &GitHubAPIError{StatusCode: resp.StatusCode, Endpoint: endpoint, Body: string(body)}
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
|
|
return "", err
|
|
}
|
|
return parseNextLink(resp.Header.Get("Link")), nil
|
|
}
|
|
|
|
// parseNextLink extracts the "next" URL path+query from a GitHub Link header.
|
|
func parseNextLink(header string) string {
|
|
if header == "" {
|
|
return ""
|
|
}
|
|
for _, part := range strings.Split(header, ",") {
|
|
part = strings.TrimSpace(part)
|
|
if !strings.Contains(part, `rel="next"`) {
|
|
continue
|
|
}
|
|
start := strings.Index(part, "<")
|
|
end := strings.Index(part, ">")
|
|
if start < 0 || end < 0 || end <= start {
|
|
continue
|
|
}
|
|
link := part[start+1 : end]
|
|
// Strip the base URL to return just the path+query for our get method
|
|
if strings.HasPrefix(link, githubAPIBase) {
|
|
return link[len(githubAPIBase):]
|
|
}
|
|
return link
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// patPR is the JSON shape from the GitHub REST API for PRs.
|
|
type patPR struct {
|
|
Number int `json:"number"`
|
|
Title string `json:"title"`
|
|
HTMLURL string `json:"html_url"`
|
|
Body string `json:"body"`
|
|
State string `json:"state"`
|
|
Draft bool `json:"draft"`
|
|
Mergeable *bool `json:"mergeable"`
|
|
MergeableState string `json:"mergeable_state"`
|
|
Additions int `json:"additions"`
|
|
Deletions int `json:"deletions"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
MergedAt *string `json:"merged_at"`
|
|
ClosedAt *string `json:"closed_at"`
|
|
RequestedReviewers []struct {
|
|
Login string `json:"login"`
|
|
} `json:"requested_reviewers"`
|
|
RequestedTeams []struct {
|
|
Slug string `json:"slug"`
|
|
Name string `json:"name"`
|
|
} `json:"requested_teams"`
|
|
User struct {
|
|
Login string `json:"login"`
|
|
} `json:"user"`
|
|
Head struct {
|
|
Ref string `json:"ref"`
|
|
SHA string `json:"sha"`
|
|
} `json:"head"`
|
|
Base struct {
|
|
Ref string `json:"ref"`
|
|
} `json:"base"`
|
|
}
|
|
|
|
type patSearchItem struct {
|
|
Number int `json:"number"`
|
|
Title string `json:"title"`
|
|
HTMLURL string `json:"html_url"`
|
|
State string `json:"state"`
|
|
Draft bool `json:"draft"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
RepositoryURL string `json:"repository_url"`
|
|
User struct {
|
|
Login string `json:"login"`
|
|
} `json:"user"`
|
|
}
|
|
|
|
func convertPatPR(raw *patPR, owner, repo string) *PR {
|
|
state := strings.ToLower(raw.State)
|
|
if raw.MergedAt != nil && *raw.MergedAt != "" {
|
|
state = prStateMerged
|
|
}
|
|
mergeable := false
|
|
if raw.Mergeable != nil {
|
|
mergeable = *raw.Mergeable
|
|
}
|
|
pr := &PR{
|
|
Number: raw.Number,
|
|
Title: raw.Title,
|
|
HTMLURL: raw.HTMLURL,
|
|
Body: raw.Body,
|
|
State: state,
|
|
HeadBranch: raw.Head.Ref,
|
|
HeadSHA: raw.Head.SHA,
|
|
BaseBranch: raw.Base.Ref,
|
|
AuthorLogin: raw.User.Login,
|
|
RepoOwner: owner,
|
|
RepoName: repo,
|
|
Draft: raw.Draft,
|
|
Mergeable: mergeable,
|
|
MergeableState: strings.ToLower(raw.MergeableState),
|
|
Additions: raw.Additions,
|
|
Deletions: raw.Deletions,
|
|
RequestedReviewers: convertPatRequestedReviewers(raw),
|
|
CreatedAt: raw.CreatedAt,
|
|
UpdatedAt: raw.UpdatedAt,
|
|
}
|
|
if raw.MergedAt != nil {
|
|
pr.MergedAt = parseTimePtr(*raw.MergedAt)
|
|
}
|
|
if raw.ClosedAt != nil {
|
|
pr.ClosedAt = parseTimePtr(*raw.ClosedAt)
|
|
}
|
|
return pr
|
|
}
|
|
|
|
func convertPatRequestedReviewers(raw *patPR) []RequestedReviewer {
|
|
reviewers := make([]RequestedReviewer, 0, len(raw.RequestedReviewers)+len(raw.RequestedTeams))
|
|
for _, reviewer := range raw.RequestedReviewers {
|
|
if reviewer.Login == "" {
|
|
continue
|
|
}
|
|
reviewers = append(reviewers, RequestedReviewer{Login: reviewer.Login, Type: reviewerTypeUser})
|
|
}
|
|
for _, team := range raw.RequestedTeams {
|
|
login := team.Slug
|
|
if login == "" {
|
|
login = team.Name
|
|
}
|
|
if login == "" {
|
|
continue
|
|
}
|
|
reviewers = append(reviewers, RequestedReviewer{Login: login, Type: reviewerTypeTeam})
|
|
}
|
|
return reviewers
|
|
}
|