This commit is contained in:
2026-10-20 02:43:27 +01:00
commit 545a9b6b88
21 changed files with 3654 additions and 0 deletions
+241
View File
@@ -0,0 +1,241 @@
// 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 <https://www.gnu.org/licenses/>.
// 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)
}
+147
View File
@@ -0,0 +1,147 @@
// 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 <https://www.gnu.org/licenses/>.
package gitea
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)
func TestAuthHeaderAndListPullFilesPagination(t *testing.T) {
var pages []int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/repos/o/r/pulls/3/files" {
t.Errorf("unexpected path %s", r.URL.Path)
}
if got := r.Header.Get("Authorization"); got != "token tok" {
t.Errorf("Authorization = %q", got)
}
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
pages = append(pages, page)
n := pageSize
if page == 2 {
n = 3
}
files := make([]File, 0, n)
for i := 0; i < n; i++ {
files = append(files, File{Filename: fmt.Sprintf("f%d-%d.go", page, i), Status: "added"})
}
_ = json.NewEncoder(w).Encode(files)
}))
defer srv.Close()
got, err := New(srv.URL, "tok").ListPullFiles(context.Background(), "o/r", 3)
if err != nil {
t.Fatal(err)
}
if len(got) != pageSize+3 {
t.Fatalf("got %d files, want %d", len(got), pageSize+3)
}
if len(pages) != 2 || pages[0] != 1 || pages[1] != 2 {
t.Fatalf("pages = %v, want [1 2]", pages)
}
}
func TestCreateStatus(t *testing.T) {
var gotMethod, gotPath, gotBody string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
w.WriteHeader(http.StatusCreated)
}))
defer srv.Close()
err := New(srv.URL, "tok").CreateStatus(context.Background(), "o/r", "abc123", "success", "license-bot / addlicense", "ok", "")
if err != nil {
t.Fatal(err)
}
if gotMethod != http.MethodPost || gotPath != "/api/v1/repos/o/r/statuses/abc123" {
t.Fatalf("%s %s", gotMethod, gotPath)
}
for _, want := range []string{`"state":"success"`, `"context":"license-bot / addlicense"`, `"description":"ok"`} {
if !strings.Contains(gotBody, want) {
t.Fatalf("body %s missing %s", gotBody, want)
}
}
}
func TestCommentLifecyclePaths(t *testing.T) {
var paths []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.Method+" "+r.URL.Path)
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodGet {
_ = json.NewEncoder(w).Encode([]Comment{{ID: 42, Body: "hi"}})
return
}
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(Comment{ID: 43})
return
}
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c := New(srv.URL, "tok")
ctx := context.Background()
if _, err := c.ListIssueComments(ctx, "o/r", 9); err != nil {
t.Fatal(err)
}
if _, err := c.CreateIssueComment(ctx, "o/r", 9, "body"); err != nil {
t.Fatal(err)
}
if err := c.EditIssueComment(ctx, "o/r", 42, "body"); err != nil {
t.Fatal(err)
}
want := []string{
"GET /api/v1/repos/o/r/issues/9/comments",
"POST /api/v1/repos/o/r/issues/9/comments",
"PATCH /api/v1/repos/o/r/issues/comments/42",
}
if len(paths) != len(want) {
t.Fatalf("paths = %v", paths)
}
for i := range want {
if paths[i] != want[i] {
t.Fatalf("paths = %v, want %v", paths, want)
}
}
}
func TestAPIErrorCarriesStatus(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "nope", http.StatusForbidden)
}))
defer srv.Close()
_, err := New(srv.URL, "tok").GetPull(context.Background(), "o/r", 1)
if err == nil {
t.Fatal("expected an error")
}
apiErr, ok := err.(*APIError)
if !ok || apiErr.Status != http.StatusForbidden {
t.Fatalf("err = %#v", err)
}
}