// Copyright (C) 2026 Dcntrlized // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . // Package gitea is a minimal Gitea REST client covering exactly the endpoints // the license bot needs. It intentionally has no third-party dependencies. package gitea import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strconv" "strings" "time" ) // Client talks to one Gitea instance. type Client struct { Base string Token string HTTP *http.Client } // New returns a client for baseURL authenticated with token. func New(baseURL, token string) *Client { return &Client{ Base: strings.TrimRight(baseURL, "/"), Token: token, HTTP: &http.Client{Timeout: 60 * time.Second}, } } // File is one entry of a pull request's changed-file list. type File struct { Filename string `json:"filename"` Status string `json:"status"` } // RepoRef is the subset of a repository object carried by a pull request. type RepoRef struct { FullName string `json:"full_name"` } // Pull is the subset of a pull request the bot relies on. type Pull struct { Number int `json:"number"` State string `json:"state"` HTMLURL string `json:"html_url"` Title string `json:"title"` Head struct { Ref string `json:"ref"` SHA string `json:"sha"` Repo RepoRef `json:"repo"` } `json:"head"` Base struct { Ref string `json:"ref"` Repo RepoRef `json:"repo"` } `json:"base"` AllowMaintainerEdit bool `json:"allow_maintainer_edit"` } // Comment is a PR/issue comment. type Comment struct { ID int64 `json:"id"` Body string `json:"body"` } // Status is one commit status entry. type Status struct { Context string `json:"context"` Status string `json:"status"` } // APIError is a non-2xx response from the Gitea API. type APIError struct { Status int Method string Path string Body string } func (e *APIError) Error() string { return fmt.Sprintf("%s %s: HTTP %d: %s", e.Method, e.Path, e.Status, e.Body) } func (c *Client) do(ctx context.Context, method, path string, in, out any) error { var body io.Reader if in != nil { b, err := json.Marshal(in) if err != nil { return err } body = bytes.NewReader(b) } req, err := http.NewRequestWithContext(ctx, method, c.Base+"/api/v1"+path, body) if err != nil { return err } req.Header.Set("Authorization", "token "+c.Token) req.Header.Set("Accept", "application/json") if in != nil { req.Header.Set("Content-Type", "application/json") } resp, err := c.HTTP.Do(req) if err != nil { return err } defer resp.Body.Close() raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if resp.StatusCode < 200 || resp.StatusCode > 299 { return &APIError{Status: resp.StatusCode, Method: method, Path: path, Body: strings.TrimSpace(string(raw))} } if out != nil && len(raw) > 0 { if err := json.Unmarshal(raw, out); err != nil { return fmt.Errorf("%s %s: decode response: %w", method, path, err) } } return nil } const pageSize = 50 // GetPull returns one pull request. func (c *Client) GetPull(ctx context.Context, repo string, index int) (*Pull, error) { var p Pull if err := c.do(ctx, http.MethodGet, "/repos/"+repo+"/pulls/"+strconv.Itoa(index), nil, &p); err != nil { return nil, err } return &p, nil } // ListOpenPulls returns every open pull request of repo. func (c *Client) ListOpenPulls(ctx context.Context, repo string) ([]Pull, error) { var all []Pull for page := 1; ; page++ { var batch []Pull p := fmt.Sprintf("/repos/%s/pulls?state=open&limit=%d&page=%d", repo, pageSize, page) if err := c.do(ctx, http.MethodGet, p, nil, &batch); err != nil { return nil, err } all = append(all, batch...) if len(batch) < pageSize { return all, nil } } } // ListPullFiles returns every changed file of a pull request. func (c *Client) ListPullFiles(ctx context.Context, repo string, index int) ([]File, error) { var all []File for page := 1; ; page++ { var batch []File p := fmt.Sprintf("/repos/%s/pulls/%d/files?limit=%d&page=%d", repo, index, pageSize, page) if err := c.do(ctx, http.MethodGet, p, nil, &batch); err != nil { return nil, err } all = append(all, batch...) if len(batch) < pageSize { return all, nil } } } // ListIssueComments returns all comments of an issue or pull request. func (c *Client) ListIssueComments(ctx context.Context, repo string, index int) ([]Comment, error) { var all []Comment for page := 1; ; page++ { var batch []Comment p := fmt.Sprintf("/repos/%s/issues/%d/comments?limit=%d&page=%d", repo, index, pageSize, page) if err := c.do(ctx, http.MethodGet, p, nil, &batch); err != nil { return nil, err } all = append(all, batch...) if len(batch) < pageSize { return all, nil } } } // CreateIssueComment posts a comment on an issue or pull request. func (c *Client) CreateIssueComment(ctx context.Context, repo string, index int, body string) (*Comment, error) { var out Comment in := map[string]string{"body": body} if err := c.do(ctx, http.MethodPost, fmt.Sprintf("/repos/%s/issues/%d/comments", repo, index), in, &out); err != nil { return nil, err } return &out, nil } // EditIssueComment updates an existing comment in place. func (c *Client) EditIssueComment(ctx context.Context, repo string, id int64, body string) error { in := map[string]string{"body": body} return c.do(ctx, http.MethodPatch, fmt.Sprintf("/repos/%s/issues/comments/%d", repo, id), in, nil) } // DeleteIssueComment removes a comment. func (c *Client) DeleteIssueComment(ctx context.Context, repo string, id int64) error { return c.do(ctx, http.MethodDelete, fmt.Sprintf("/repos/%s/issues/comments/%d", repo, id), nil, nil) } // ListStatuses returns every commit status of one commit. func (c *Client) ListStatuses(ctx context.Context, repo, sha string) ([]Status, error) { var all []Status for page := 1; ; page++ { var batch []Status p := fmt.Sprintf("/repos/%s/commits/%s/statuses?limit=%d&page=%d", repo, url.PathEscape(sha), pageSize, page) if err := c.do(ctx, http.MethodGet, p, nil, &batch); err != nil { return nil, err } all = append(all, batch...) if len(batch) < pageSize { return all, nil } } } // CreateStatus posts a commit status. state is one of pending, success, // failure, error, warning. func (c *Client) CreateStatus(ctx context.Context, repo, sha, state, context, description, targetURL string) error { in := map[string]string{"state": state, "context": context, "description": description} if targetURL != "" { in["target_url"] = targetURL } return c.do(ctx, http.MethodPost, fmt.Sprintf("/repos/%s/statuses/%s", repo, url.PathEscape(sha)), in, nil) }