refactor: move the transport onto the official Gitea SDK

The transport was hand-rolled net/http against the REST API. The payload shapes
were ours, in internal/wire, which meant every field Gitea learned was a field
somebody here had to notice; and "does this instance have issue dependencies?"
had to be guessed from a status code, because a 404 from a missing route and a
404 from a missing issue look alike.

The SDK settles both. The shapes are maintained by the people who maintain the
server, and the client negotiates the server's version when it is built, so the
dependency endpoint is now gated on `>= 1.20.0` — verified against the release
where the route appears, not assumed. Below the gate nothing is requested at all.

internal/wire keeps what the SDK has no answer for: addressing. The SDK takes an
owner, a name and an int64 and never parses, while `42`, `#42`, `owner/repo#42`
and an issue URL are four spellings of one address, all four are what somebody
has in hand, and Key is what the ledger is keyed by. The payload structs go.

Four things that had to survive the move, and did:

- request bodies still land in .kettle/payload/, now via an http.RoundTripper on
  the client the SDK is given — which is better than before, because it files
  every request rather than the ones a call site remembered to name;
- errors still carry the HTTP status AND the response body, and a decode failure
  on a 2xx is deliberately not an APIError, so the dependency probe cannot read
  a bad decode as "feature missing";
- the number -> slug ledger is untouched, entries still outlive the files they
  name;
- Client.For(repo) still re-points at another repository for one call.

What it cost, written down in AGENTS.md where it happened. internal/mapping's
layering test was a fact about the import graph — nothing in its closure could
open a socket — and the SDK ships its types and its client in one package, so
the test now asserts what is still true: the bridge performs no I/O, checked on
direct imports plus a grep for time.Now. A run makes one extra request before it
does anything. Gitea's issue edit endpoint carries no labels, so a push whose
labels changed needs a second call; push makes it and says so. go.mod requires
go 1.26, which the SDK sets and which is now the floor for building this binary.

internal/issue and internal/project are byte-identical. The domain did not
notice, which is the whole argument for the layering.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
naudachu
2026-08-11 19:29:38 +05:00
parent 9480e48312
commit 1239fdee70
292 changed files with 51205 additions and 864 deletions
+273 -151
View File
@@ -10,17 +10,25 @@
// that layer is not imported here either: it sits above this package, not
// beside it.
//
// The JSON shapes and the issue keys are internal/wire's. They are not this
// package's to own, because the bridge needs exactly the same vocabulary and
// cannot import a transport to get it; a copy on each side is two structs that
// drift and a command that copies fields between them by hand.
// The payload shapes are code.gitea.io/sdk/gitea's, aliased `sdk` everywhere it
// is imported so that one type has one spelling across the tree. They are not
// this package's to own and never were: the bridge needs exactly the same
// vocabulary and cannot import a transport to get it, and a copy on each side
// is two structs that drift and a command that copies fields between them by
// hand. The issue KEYS are still internal/wire's — the SDK addresses an issue
// as (owner, repo, int64) and never parses `owner/repo#42` out of anything.
//
// Every request goes through Call. One place sets the header, one place reads
// a status code, one place files the request body. When this was a Python
// module shelling out to `tea api`, "why did that fail" meant reading a
// subprocess's stderr and guessing; here a failure is an *APIError carrying the
// status AND the body the server actually sent, because "500" on its own has
// never helped anybody.
// WHAT THIS PACKAGE IS, NOW THAT THE SDK EXISTS: the one place that holds the
// credentials, the scratchpad and the repository this project points at, so
// that no command has to. Every method here is a thin wrapper, and the three
// things the wrapping is for are the three things the SDK does not do:
//
// - every request body is filed under `.kettle/payload/` by a RoundTripper,
// so a retry or a post-mortem has the bytes that went out;
// - every failure comes back as an *APIError carrying the status AND what the
// server said, because "500" on its own has never helped anybody;
// - a listing stops when the caller has what it asked for, which a client
// that fetches whole pages into a slice cannot do.
package gitea
import (
@@ -30,21 +38,21 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unicode/utf8"
sdk "code.gitea.io/sdk/gitea"
"git.noodles.cam/claude-skills/marketplace/cli/internal/config"
"git.noodles.cam/claude-skills/marketplace/cli/internal/project"
"git.noodles.cam/claude-skills/marketplace/cli/internal/wire"
)
const (
// apiPrefix is where every Gitea instance puts its REST API.
apiPrefix = "/api/v1"
// userAgent names this binary in the server's log. A tracker admin looking
// at a burst of requests should be able to tell what made them.
userAgent = "kettle"
@@ -59,25 +67,28 @@ const (
// Client talks to one repository on one Gitea instance.
type Client struct {
// HTTP is the transport, exported so a caller can change the timeout or
// hand in an instrumented one. Never nil after New.
HTTP *http.Client
// api is the SDK client: one per run, shared by every copy For makes.
api *sdk.Client
// http is the SDK's transport, kept because AddDependency still sends one
// request by hand — see there.
http *http.Client
// dump is the RoundTripper that files request bodies. Shared with every
// copy For makes, because the scratchpad is one directory per run.
dump *dumper
base string // instance URL with the API prefix, no trailing slash
base string // instance URL, no API prefix and no trailing slash
token string
repo wire.Repo
// payloadRoot is resolved once, by New, and is never taken from a caller.
// The one time where a request body lands was an argument, it got pointed
// at the issue store — see writePayload.
payloadRoot string
}
// New builds a client for the repository this project points at.
//
// It refuses a half-filled configuration instead of letting the first call come
// back 401 or 404: those answers name nothing an operator can act on, and every
// field missing here has exactly one command that supplies it.
// field missing here has exactly one command that supplies it. That check comes
// first because building the client now DIALS — the SDK asks the instance for
// its version before it hands one back — and a missing token reported as a
// connection failure sends the operator to the wrong place.
func New(cfg *config.Resolved) (*Client, error) {
if cfg == nil {
return nil, errors.New("no resolved configuration — call config.Require first")
@@ -95,98 +106,61 @@ func New(cfg *config.Resolved) (*Client, error) {
if len(missing) > 0 {
return nil, fmt.Errorf("this project has no %s", strings.Join(missing, ", and no "))
}
base := strings.TrimRight(cfg.URL, "/")
dump := &dumper{next: http.DefaultTransport, root: project.PayloadRoot("")}
hc := &http.Client{Timeout: requestTimeout, Transport: dump}
api, err := sdk.NewClient(base,
sdk.SetToken(cfg.Token),
sdk.SetHTTPClient(hc),
sdk.SetUserAgent(userAgent))
if err != nil {
// A version string the SDK cannot parse is not a cosmetic failure, and
// it is refused here rather than shrugged off: the SDK hands back a
// usable-looking client that has quietly decided the server is Gitea
// 1.11, and its 1.11 compatibility path rewrites an issue's URL from a
// `repository` field a modern payload need not carry — a nil
// dereference on the first issue read. Saying so at the handshake beats
// crashing three calls later.
if errors.Is(err, &sdk.ErrUnknownVersion{}) {
return nil, fmt.Errorf("%s did not answer with a version this can read (%w)"+
" — check that %s points at a Gitea instance", base, err, config.EnvURL)
}
return nil, fmt.Errorf("cannot reach the Gitea instance at %s: %w", base, err)
}
return &Client{
HTTP: &http.Client{Timeout: requestTimeout},
base: strings.TrimRight(cfg.URL, "/") + apiPrefix,
token: cfg.Token,
repo: wire.Repo{Owner: cfg.Owner, Name: cfg.Repo},
payloadRoot: project.PayloadRoot(""),
api: api,
http: hc,
dump: dump,
base: base,
token: cfg.Token,
repo: wire.Repo{Owner: cfg.Owner, Name: cfg.Repo},
}, nil
}
// Repo is the repository every path is built against.
// Repo is the repository every call is made against.
func (c *Client) Repo() wire.Repo { return c.repo }
// For returns a copy of this client pointed at another repository, for the run
// that was given an explicit owner/name. The credentials and the scratchpad
// come along; only the paths change.
// that was given an explicit owner/name.
//
// Bookkeeping and not a second connection: the SDK takes the owner and the name
// per call, so what changes is which pair this client passes. The credentials,
// the negotiated server version and the scratchpad are all shared, which is
// what makes `kettle pull owner/repo#42` cost nothing extra.
func (c *Client) For(r wire.Repo) *Client {
out := *c
out.repo = r
return &out
}
// Body is a request payload and the name its dump is filed under.
//
// The name is the caller's label for this call, not a path: it becomes
// `<name>.json` in the scratchpad, and something that identifies the call in a
// post-mortem — an issue's slug, a label's name — is worth more there than a
// serial number.
type Body struct {
Name string
Data any
}
// owned is the owner and name every SDK call takes, escaped by the SDK itself.
func (c *Client) owned() (string, string) { return c.repo.Owner, c.repo.Name }
// Call makes one request and decodes the answer into out, which may be nil when
// there is nothing to read.
//
// body may be nil. When it is not, its Data is marshalled once: the bytes filed
// in the scratchpad and the bytes on the wire are the same bytes, so a retry
// from the file sends what this call sent.
//
// An empty response body leaves out untouched — a 204 from a PATCH is a
// success, not a decode failure.
func (c *Client) Call(method, path string, body *Body, out any) error {
var payload []byte
if body != nil {
var err error
if payload, err = c.writePayload(body); err != nil {
return err
}
}
endpoint := c.base + "/" + strings.TrimLeft(path, "/")
var reader io.Reader
if payload != nil {
reader = bytes.NewReader(payload)
}
req, err := http.NewRequest(method, endpoint, reader)
if err != nil {
return fmt.Errorf("%s %s: %w", method, endpoint, err)
}
// Gitea's own scheme, and what the `tea` CLI this replaces sent: the word
// `token`, not `Bearer`. An instance answers 401 to the other spelling.
req.Header.Set("Authorization", "token "+c.token)
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", userAgent)
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.HTTP.Do(req)
if err != nil {
// The token travels in a header and never in the URL, so an error is
// free to quote the URL in full.
return fmt.Errorf("%s %s: %w", method, endpoint, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("%s %s: reading the response: %w", method, endpoint, err)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return &APIError{Method: method, URL: endpoint, Status: resp.StatusCode, Body: string(raw)}
}
if out == nil || len(bytes.TrimSpace(raw)) == 0 {
return nil
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("%s %s: %d answered with what is not the JSON expected (%w): %s",
method, endpoint, resp.StatusCode, err, truncate(string(raw)))
}
return nil
}
// --------------------------------------------------------------------------
// what a failure says
// --------------------------------------------------------------------------
// APIError is a non-2xx answer, carrying both halves of what happened.
//
@@ -223,6 +197,36 @@ func StatusIs(err error, status int) bool {
return errors.As(err, &apiErr) && apiErr.Status == status
}
// fail turns one SDK call's (response, error) pair into this package's error.
//
// BOTH HALVES OR NEITHER. The SDK reads the response body to build its error
// and then closes it, so the body is only ever available through err; the
// status and the request line are only ever available through resp. Neither is
// a diagnosis on its own, and dropping either is how "the tracker said no"
// becomes a message nobody can act on.
//
// A 2xx that still errored is a decode failure, not an answer the server
// refused: it keeps the status out of the message and the shape out of
// StatusIs, because a caller asking "was that a 409" must not be told yes by a
// body it could not parse.
func fail(resp *sdk.Response, err error) error {
if err == nil {
return nil
}
if resp == nil || resp.Response == nil {
return err // never reached the server; the URL is already in the error
}
method, endpoint := "", ""
if r := resp.Request; r != nil {
method, endpoint = r.Method, r.URL.String()
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return &APIError{Method: method, URL: endpoint, Status: resp.StatusCode, Body: err.Error()}
}
return fmt.Errorf("%s %s: %d answered with what is not the JSON expected: %w",
method, endpoint, resp.StatusCode, err)
}
func truncate(s string) string {
if len(s) <= maxErrorBody {
return s
@@ -240,11 +244,17 @@ func truncate(s string) string {
// where request bodies land
// --------------------------------------------------------------------------
// writePayload marshals a request body, files a copy under `.kettle/payload/`,
// and returns the bytes to send.
// dumper is the RoundTripper that files a copy of every request body under
// `.kettle/payload/`.
//
// The file survives the call, for a retry or a post-mortem.
//
// A RoundTripper and not a call site's decision, because a call site can forget
// and a RoundTripper cannot: it sees every request the SDK builds, including
// the ones no method of this package spelled out. What a call site still
// supplies is the NAME — see label — because an issue's slug identifies the
// call in a post-mortem and a serial number does not.
//
// WHERE IT LANDS IS NOT THE CALLER'S BUSINESS, and never was. The directory is
// this package's scratchpad — a SIBLING of the issue store under the same
// marker, resolved by the same walk, so which command wrote a body cannot
@@ -255,58 +265,179 @@ func truncate(s string) string {
// are debris of the transport, and when they share a path `ls` starts lying
// about what the project holds.
//
// It is created lazily, by the first write of a run and only then, so a dry run
// or a run with nothing to send leaves no directory behind.
func (c *Client) writePayload(b *Body) ([]byte, error) {
if c.payloadRoot == "" {
return nil, project.NotFoundError("")
// It is created lazily, by the first write of a run and only then, so a run
// with nothing to send — every read-only command, and the version handshake
// every run opens with — leaves no directory behind.
type dumper struct {
next http.RoundTripper
// root is resolved once, by New, and is never taken from a caller.
root string
mu sync.Mutex
name string
}
// label names the file the next request body lands in. One label serves one
// request: it is taken, not read, so a request the SDK makes on its own account
// cannot end up filed under the last thing a command was doing.
func (d *dumper) label(name string) {
d.mu.Lock()
d.name = name
d.mu.Unlock()
}
func (d *dumper) take() string {
d.mu.Lock()
defer d.mu.Unlock()
name := d.name
d.name = ""
return name
}
// RoundTrip files the body and then sends the request.
//
// A dump that cannot be written fails the call before it is made, which is the
// order the old hand-rolled client had and worth keeping: the point of the file
// is to hold what was sent, and one that does not exist for a request that did
// is worse than not having sent it.
func (d *dumper) RoundTrip(req *http.Request) (*http.Response, error) {
if err := d.file(req); err != nil {
return nil, err
}
return d.next.RoundTrip(req)
}
func (d *dumper) file(req *http.Request) error {
name := d.take()
if req.Body == nil || req.GetBody == nil {
return nil // a read: nothing to file
}
body, err := req.GetBody()
if err != nil {
return err
}
defer body.Close()
raw, err := io.ReadAll(body)
if err != nil {
return err
}
if len(bytes.TrimSpace(raw)) == 0 {
return nil
}
if d.root == "" {
return project.NotFoundError("")
}
if name == "" {
name = derivedName(req)
}
if err := os.MkdirAll(d.root, 0o755); err != nil {
return err
}
return os.WriteFile(filepath.Join(d.root, safeName(name)+".json"), readable(raw), 0o644)
}
// readable is the request body as a person reads it: indented, and with the
// markup left alone.
//
// The SDK marshals with encoding/json's defaults, which escape `<`, `>` and `&`
// into their \u00xx spellings. An issue body carries `<!-- … -->` markers and
// prose full of `&`, and a dump escaped that way is unreadable exactly when
// somebody is reading it because something went wrong.
//
// So the bytes are re-encoded rather than filed verbatim: same JSON VALUE, and
// numbers verbatim (UseNumber, so an id is not rounded through a float), but
// not the same bytes. What that costs is byte-for-byte fidelity with the wire —
// what it buys is a file anybody can read and re-POST. Anything that will not
// parse is filed as it came, because a dump of something surprising is exactly
// the dump worth having.
func readable(raw []byte) []byte {
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
var v any
if err := dec.Decode(&v); err != nil {
return raw
}
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
// An issue body carries `<!-- … -->` markers and prose full of `&`.
// Escaping those to < would make the dump unreadable exactly when
// somebody is reading it because something went wrong.
enc.SetEscapeHTML(false)
if err := enc.Encode(b.Data); err != nil {
return nil, fmt.Errorf("encoding the %s request body: %w", b.name(), err)
if err := enc.Encode(v); err != nil {
return raw
}
raw := buf.Bytes()
if err := os.MkdirAll(c.payloadRoot, 0o755); err != nil {
return nil, err
}
path := filepath.Join(c.payloadRoot, b.name()+".json")
if err := os.WriteFile(path, raw, 0o644); err != nil {
return nil, err
}
return raw, nil
return buf.Bytes()
}
// name is the file stem, with everything that is not plainly a file name folded
// away.
// derivedName is what an unnamed request is filed under: its method and its
// path. Nobody has to remember to name a call for its body to be kept — a name
// only makes the file easier to find.
func derivedName(req *http.Request) string {
return strings.ToLower(req.Method) + "-" + strings.TrimPrefix(req.URL.Path, "/api/v1/")
}
// safeName is the file stem, with everything that is not plainly a file name
// folded away.
//
// Sanitizing here rather than trusting callers: label names are namespaced
// (`type/bug`), and a name passed straight through would write outside the
// scratchpad — which is the one thing this directory exists to prevent.
func (b *Body) name() string {
if b.Name == "" {
return "request"
}
func safeName(name string) string {
safe := strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
return r
}
return '-'
}, b.Name)
}, name)
if safe = strings.Trim(safe, "-"); safe == "" {
return "request"
}
return safe
}
// --------------------------------------------------------------------------
// the one request the SDK cannot express
// --------------------------------------------------------------------------
// post sends one JSON body to a path under this instance's API and ignores
// whatever comes back.
//
// It exists for AddDependency and for nothing else — see there for what the SDK
// leaves out. It goes through the same http.Client, so the body is filed and a
// failure carries the status and the server's words exactly as every other call
// in this package does.
func (c *Client) post(path string, body any, name string) error {
raw, err := json.Marshal(body)
if err != nil {
return err
}
endpoint := c.base + "/api/v1/" + strings.TrimLeft(path, "/")
req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(raw))
if err != nil {
return err
}
// Gitea's own scheme, and what the `tea` CLI this replaces sent: the word
// `token`, not `Bearer`. An instance answers 401 to the other spelling.
req.Header.Set("Authorization", "token "+c.token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", userAgent)
c.dump.label(name)
resp, err := c.http.Do(req)
if err != nil {
// The token travels in a header and never in the URL, so an error is
// free to quote the URL in full.
return err
}
defer resp.Body.Close()
answer, _ := io.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return &APIError{Method: http.MethodPost, URL: endpoint, Status: resp.StatusCode, Body: string(answer)}
}
return nil
}
// --------------------------------------------------------------------------
// pagination
// --------------------------------------------------------------------------
@@ -327,21 +458,19 @@ const (
PageSlack = 4
)
// pages GETs a list endpoint page by page and hands each page to each as it
// arrives, stopping when each returns false, when a short page says the list is
// pages calls fetch page by page and hands each page to each as it arrives,
// stopping when each returns false, when a short page says the list is
// exhausted, or when budget pages have been read.
//
// A callback rather than a slice, because a caller whose budget is spent on
// what it KEEPS cannot be served by a function that fetches everything first:
// the page after the one that completed the budget must never be requested.
func pages[T any](c *Client, path string, limit, budget int, each func([]T) (bool, error)) error {
sep := "?"
if strings.Contains(path, "?") {
sep = "&"
}
// That is the one thing the SDK's own list options cannot do — they describe a
// page, and this describes when to stop asking for another.
func pages[T any](fetch func(page, limit int) ([]T, error), limit, budget int, each func([]T) (bool, error)) error {
for page := 1; page <= budget; page++ {
var batch []T
if err := c.Call(http.MethodGet, fmt.Sprintf("%s%spage=%d&limit=%d", path, sep, page, limit), nil, &batch); err != nil {
batch, err := fetch(page, limit)
if err != nil {
return err
}
if len(batch) == 0 {
@@ -359,23 +488,16 @@ func pages[T any](c *Client, path string, limit, budget int, each func([]T) (boo
}
// paginate follows a list endpoint to exhaustion and returns the whole list.
func paginate[T any](c *Client, path string, limit int) ([]T, error) {
func paginate[T any](fetch func(page, limit int) ([]T, error), limit int) ([]T, error) {
var out []T
err := pages(c, path, limit, maxPages, func(batch []T) (bool, error) {
err := pages(fetch, limit, maxPages, func(batch []T) (bool, error) {
out = append(out, batch...)
return true, nil
})
return out, err
}
// repoPath builds an endpoint under this client's repository. Owner and name
// are escaped: they arrive from a config file, and a file is a thing people
// type into.
func (c *Client) repoPath(suffix string) string {
return "repos/" + url.PathEscape(c.repo.Owner) + "/" + url.PathEscape(c.repo.Name) + "/" + suffix
}
// repoPathf is repoPath with the issue or label number formatted in.
func (c *Client) repoPathf(format string, args ...any) string {
return c.repoPath(fmt.Sprintf(format, args...))
// listOptions is one page, as the SDK asks for it.
func listOptions(page, limit int) sdk.ListOptions {
return sdk.ListOptions{Page: page, PageSize: limit}
}
+220 -41
View File
@@ -9,6 +9,12 @@ package gitea_test
// — and a request dump would land in the developer's own project. Nothing here
// reads a login file either, but KETTLE_CONFIG_HOME is redirected all the same,
// so a run can neither read nor overwrite the developer's own tokens.
//
// EVERY FAKE ANSWERS /api/v1/version, because building a client is now a
// request: the SDK asks the instance what it is before it hands one back, and
// that answer is what the dependency gate is decided on later. A fake that did
// not answer it would be a fake no client can be built against — see
// versionRoute.
import (
"encoding/json"
@@ -19,15 +25,22 @@ import (
"os"
"os/exec"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
sdk "code.gitea.io/sdk/gitea"
"git.noodles.cam/claude-skills/marketplace/cli/internal/config"
"git.noodles.cam/claude-skills/marketplace/cli/internal/gitea"
"git.noodles.cam/claude-skills/marketplace/cli/internal/wire"
)
// modernGitea is what a fake says it is: new enough for everything this
// transport asks for, dependency endpoints included.
const modernGitea = "1.26.1"
// newProject makes an initialized project and points the walk at it. Returns
// the project root.
func newProject(t *testing.T) string {
@@ -41,6 +54,31 @@ func newProject(t *testing.T) string {
return dir
}
// versionRoute answers the SDK's version handshake and reports whether it did,
// so every other handler can be written as though the request were not there.
func versionRoute(w http.ResponseWriter, r *http.Request, version string) bool {
if r.URL.Path != "/api/v1/version" {
return false
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"version":"`+version+`"}`)
return true
}
// serve is an httptest server that speaks the handshake and hands everything
// else to next.
func serve(t *testing.T, version string, next http.HandlerFunc) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if versionRoute(w, r, version) {
return
}
next(w, r)
}))
t.Cleanup(srv.Close)
return srv
}
func newClient(t *testing.T, url string) *gitea.Client {
t.Helper()
c, err := gitea.New(&config.Resolved{URL: url, Token: "s3cret", Owner: "acme", Repo: "widgets"})
@@ -65,7 +103,7 @@ func TestPaginationFollowsToTheLastPage(t *testing.T) {
var asked []string
var auth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
asked = append(asked, r.URL.RequestURI())
auth = r.Header.Get("Authorization")
@@ -82,8 +120,7 @@ func TestPaginationFollowsToTheLastPage(t *testing.T) {
out = append(out, map[string]any{"id": (page-1)*limit + i + 1, "body": "hello"})
}
writeJSON(t, w, out)
}))
defer srv.Close()
})
got, err := newClient(t, srv.URL).ListComments(42)
if err != nil {
@@ -102,7 +139,7 @@ func TestPaginationFollowsToTheLastPage(t *testing.T) {
if auth != "token s3cret" {
t.Errorf("Authorization was %q, want %q", auth, "token s3cret")
}
want := "/api/v1/repos/acme/widgets/issues/42/comments?page=1&limit=50"
want := "/api/v1/repos/acme/widgets/issues/42/comments?limit=50&page=1"
if asked[0] != want {
t.Errorf("first request was %s, want %s", asked[0], want)
}
@@ -113,11 +150,10 @@ func TestPaginationFollowsToTheLastPage(t *testing.T) {
func TestErrorNamesTheStatusAndTheBody(t *testing.T) {
newProject(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnprocessableEntity)
io.WriteString(w, `{"message":"label already exists","url":"https://example.test/docs"}`)
}))
defer srv.Close()
})
_, err := newClient(t, srv.URL).GetIssue(7)
if err == nil {
@@ -152,21 +188,20 @@ func TestPayloadLandsBesideTheStoreAndNeverInIt(t *testing.T) {
root := newProject(t)
var sent []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
sent, _ = io.ReadAll(r.Body)
writeJSON(t, w, map[string]any{
"number": 42, "id": 5, "html_url": "https://example.test/acme/widgets/issues/42"})
}))
defer srv.Close()
})
body := "<!-- kettle:id wire-sqlc --> a & b"
got, err := newClient(t, srv.URL).CreateIssue(
wire.IssueRequest{Title: wire.Set("wire sqlc"), Body: wire.Set(body)}, "issue-wire-sqlc")
sdk.CreateIssueOption{Title: "wire sqlc", Body: body}, "issue-wire-sqlc")
if err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if got.Number != 42 {
t.Errorf("got issue #%d, want #42", got.Number)
if got.Index != 42 {
t.Errorf("got issue #%d, want #42", got.Index)
}
path := filepath.Join(root, ".kettle", "payload", "issue-wire-sqlc.json")
@@ -174,19 +209,33 @@ func TestPayloadLandsBesideTheStoreAndNeverInIt(t *testing.T) {
if err != nil {
t.Fatalf("the request body was not filed at %s: %v", path, err)
}
if string(raw) != string(sent) {
// The same JSON VALUE as went out, and not the same bytes: the SDK marshals
// with encoding/json's defaults, so what is on the wire has its markup
// escaped and no indentation. A dump nobody can read is a dump nobody
// reads, and a re-POST of this file sends what this call sent.
var filed, onTheWire any
if err := json.Unmarshal(raw, &filed); err != nil {
t.Fatalf("the filed body is not JSON: %v\n%s", err, raw)
}
if err := json.Unmarshal(sent, &onTheWire); err != nil {
t.Fatalf("what was sent is not JSON: %v\n%s", err, sent)
}
if !reflect.DeepEqual(filed, onTheWire) {
t.Errorf("the filed body is not the body that was sent:\nfiled: %s\nsent: %s", raw, sent)
}
// A dump escaped to \u003c is unreadable exactly when it is being read.
if !strings.Contains(string(raw), "<!-- kettle:id wire-sqlc --> a & b") {
t.Errorf("the dump escaped the markup it was meant to preserve:\n%s", raw)
}
if !strings.Contains(string(raw), "\n \"") {
t.Errorf("the dump is not indented:\n%s", raw)
}
// The whole reason the scratchpad is a sibling.
if _, err := os.Stat(filepath.Join(root, ".kettle", "issues")); !os.IsNotExist(err) {
t.Errorf("writing a request body materialized the issue store (%v)", err)
}
// A namespaced name must not climb out of the scratchpad.
if _, err := newClient(t, srv.URL).CreateLabel(wire.LabelRequest{Name: "type/bug", Color: "#ee0701"}); err != nil {
if _, err := newClient(t, srv.URL).CreateLabel(sdk.CreateLabelOption{Name: "type/bug", Color: "#ee0701"}); err != nil {
t.Fatalf("CreateLabel: %v", err)
}
if _, err := os.Stat(filepath.Join(root, ".kettle", "payload", "label-type-bug.json")); err != nil {
@@ -198,14 +247,14 @@ func TestPayloadLandsBesideTheStoreAndNeverInIt(t *testing.T) {
}
// A run that sends no body leaves no directory behind — the scratchpad is
// created by the first write and only then.
// created by the first write and only then. The version handshake every client
// opens with is a read, so building one is not "a run that sent something".
func TestAReadOnlyCallCreatesNoScratchpad(t *testing.T) {
root := newProject(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
writeJSON(t, w, map[string]any{"number": 42})
}))
defer srv.Close()
})
if _, err := newClient(t, srv.URL).GetIssue(42); err != nil {
t.Fatalf("GetIssue: %v", err)
@@ -221,7 +270,7 @@ func TestAReadOnlyCallCreatesNoScratchpad(t *testing.T) {
func TestListIssuesRechecksWhatTheServerIgnored(t *testing.T) {
newProject(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/milestones") {
writeJSON(t, w, []map[string]any{{"id": 3, "title": "v1"}, {"id": 9, "title": "later"}})
return
@@ -237,8 +286,7 @@ func TestListIssuesRechecksWhatTheServerIgnored(t *testing.T) {
{"number": 4, "title": "a pull request", "milestone": map[string]any{"id": 3, "title": "v1"},
"pull_request": map[string]any{"merged": false}},
})
}))
defer srv.Close()
})
got, err := newClient(t, srv.URL).ListIssues(gitea.IssueFilter{Milestone: "v1", Limit: 50})
if err != nil {
@@ -247,7 +295,7 @@ func TestListIssuesRechecksWhatTheServerIgnored(t *testing.T) {
if got.Milestone != "v1" {
t.Errorf("resolved milestone is %q, want v1", got.Milestone)
}
if len(got.Issues) != 1 || got.Issues[0].Number != 1 {
if len(got.Issues) != 1 || got.Issues[0].Index != 1 {
t.Fatalf("got %d issue(s) %v, want only #1 — the backlog was not re-filtered", len(got.Issues), got.Issues)
}
@@ -265,7 +313,7 @@ func TestListIssuesStopsAtThePageBudget(t *testing.T) {
newProject(t)
pages := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
pages++
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
out := []map[string]any{}
@@ -273,12 +321,11 @@ func TestListIssuesStopsAtThePageBudget(t *testing.T) {
out = append(out, map[string]any{"number": pages*100 + i, "state": "closed"})
}
writeJSON(t, w, out)
}))
defer srv.Close()
})
got, err := newClient(t, srv.URL).ListIssues(gitea.IssueFilter{
Limit: 2,
Keep: func(i *wire.Issue) bool { return i.State == "open" },
Keep: func(i *sdk.Issue) bool { return i.State == sdk.StateOpen },
})
if err != nil {
t.Fatalf("ListIssues: %v", err)
@@ -302,7 +349,7 @@ func TestListIssuesStopsAtTheLimit(t *testing.T) {
newProject(t)
pages := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
pages++
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
out := []map[string]any{}
@@ -310,12 +357,11 @@ func TestListIssuesStopsAtTheLimit(t *testing.T) {
out = append(out, map[string]any{"number": pages*100 + i, "state": "open"})
}
writeJSON(t, w, out)
}))
defer srv.Close()
})
got, err := newClient(t, srv.URL).ListIssues(gitea.IssueFilter{
Limit: 2,
Keep: func(i *wire.Issue) bool { return i.State == "open" },
Keep: func(i *sdk.Issue) bool { return i.State == sdk.StateOpen },
})
if err != nil {
t.Fatalf("ListIssues: %v", err)
@@ -328,29 +374,122 @@ func TestListIssuesStopsAtTheLimit(t *testing.T) {
}
}
// A dependency endpoint the instance does not have is "no dependencies", not a
// failed pull. A dead connection still is one.
// A dependency endpoint the instance has but this repository does not is "no
// dependencies", not a failed pull. A dead connection still is one.
func TestDependenciesToleratesAnInstanceWithoutThem(t *testing.T) {
newProject(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "not implemented", http.StatusNotImplemented)
}))
defer srv.Close()
})
got, err := newClient(t, srv.URL).DependencyKeys(42)
// Both clients are built while the server is up, because building one is
// itself a request now — and the question this asks is what a call does
// when the connection dies UNDER it, which is a different failure from a
// tracker that was never there.
live := newClient(t, srv.URL)
dead := newClient(t, srv.URL)
got, err := live.DependencyKeys(42)
if err != nil || len(got) != 0 {
t.Errorf("DependencyKeys = %v, %v; want no keys and no error", got, err)
}
srv.Close()
if _, err := newClient(t, srv.URL).Dependencies(42); err == nil {
if _, err := dead.Dependencies(42); err == nil {
t.Error("a dead connection was reported as an instance without dependency support")
}
}
// The gate the SDK made possible: an instance too old to have the endpoint at
// all is answered from its version, without a request.
//
// It matters because the alternative is guessing from a status code. An old
// Gitea answers a route it does not have with the same 404 it answers for an
// issue that does not exist, and a pull that read the second as "no blockers"
// would quietly drop half the unit of work.
func TestDependenciesAreNotAskedForOnAnInstanceTooOldToHaveThem(t *testing.T) {
newProject(t)
asked := 0
srv := serve(t, "1.19.4", func(w http.ResponseWriter, r *http.Request) {
asked++
writeJSON(t, w, []map[string]any{{"number": 7}})
})
c := newClient(t, srv.URL)
got, err := c.Dependencies(42)
if err != nil || len(got) != 0 {
t.Errorf("Dependencies = %v, %v; want none and no error", got, err)
}
if asked != 0 {
t.Errorf("%d request(s) went out — the version had already answered", asked)
}
// Writing one says so out loud instead: push reports it beside the issue it
// could not link, and a warning naming the version is something an operator
// can act on.
err = c.AddDependency(42, wire.Key{Repo: wire.Repo{Owner: "acme", Name: "widgets"}, Number: 7})
if err == nil {
t.Fatal("a link was attempted against an instance that has no endpoint for it")
}
if !strings.Contains(err.Error(), "1.20.0") {
t.Errorf("the refusal does not name the version that would work: %v", err)
}
if asked != 0 {
t.Errorf("%d request(s) went out for a write the instance cannot take", asked)
}
}
// And the other side of the same gate: a modern instance is asked, and the
// answer comes back as cross-repo keys — a dependency is allowed to live
// somewhere else, and a bare number would not say where.
func TestDependenciesAreAskedForOnAnInstanceThatHasThem(t *testing.T) {
newProject(t)
var body string
srv := serve(t, modernGitea, func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
raw, _ := io.ReadAll(r.Body)
body = string(raw)
w.WriteHeader(http.StatusCreated)
return
}
writeJSON(t, w, []map[string]any{
{"number": 7},
{"number": 3, "repository": map[string]any{"full_name": "other/repo"}},
})
})
c := newClient(t, srv.URL)
got, err := c.DependencyKeys(42)
if err != nil {
t.Fatalf("DependencyKeys: %v", err)
}
want := []wire.Key{
{Repo: wire.Repo{Owner: "acme", Name: "widgets"}, Number: 7},
{Repo: wire.Repo{Owner: "other", Name: "repo"}, Number: 3},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("keys = %v, want %v", got, want)
}
// The one endpoint left with a hand-rolled request, because the SDK's
// IssueMeta carries an index and nothing else: a link to another repository
// needs the owner and the name with it.
if err := c.AddDependency(42, want[1]); err != nil {
t.Fatalf("AddDependency: %v", err)
}
for _, part := range []string{`"index":3`, `"owner":"other"`, `"repo":"repo"`} {
if !strings.Contains(body, part) {
t.Errorf("the link body does not carry %s: %s", part, body)
}
}
}
// A half-filled configuration is refused here rather than at the first 401,
// because a 401 names nothing an operator can act on.
// because a 401 names nothing an operator can act on — and before the client is
// built at all, because building one dials.
func TestNewRefusesAHalfFilledConfiguration(t *testing.T) {
for _, tc := range []struct {
what string
@@ -372,14 +511,54 @@ func TestNewRefusesAHalfFilledConfiguration(t *testing.T) {
}
}
// An instance nobody can reach is named as one. The handshake is the first
// request of every run, so this is the failure an operator meets when the URL
// is wrong or the tracker is down, and it has to say which instance.
func TestNewSaysWhichInstanceItCouldNotReach(t *testing.T) {
newProject(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
srv.Close()
_, err := gitea.New(&config.Resolved{URL: srv.URL, Token: "t", Owner: "a", Repo: "b"})
if err == nil {
t.Fatal("a client was built against a tracker that is not there")
}
if !strings.Contains(err.Error(), srv.URL) {
t.Errorf("the error does not name the instance: %v", err)
}
}
// A version nobody can parse is refused at the handshake, not carried.
//
// The SDK hands back a client that has silently decided the server is 1.11 and
// then rewrites issue URLs from a field a modern payload need not carry, which
// is a nil dereference on the first issue read. A refusal that names the
// instance is the answer an operator can act on.
func TestNewRefusesAnInstanceWhoseVersionIsNotOne(t *testing.T) {
newProject(t)
srv := serve(t, "not-a-version", func(w http.ResponseWriter, r *http.Request) {
t.Errorf("a call went out to %s after the handshake had already failed", r.URL.Path)
})
_, err := gitea.New(&config.Resolved{URL: srv.URL, Token: "t", Owner: "a", Repo: "b"})
if err == nil {
t.Fatal("an unreadable version was accepted — the first issue read would panic inside the SDK")
}
if !strings.Contains(err.Error(), srv.URL) || !strings.Contains(err.Error(), config.EnvURL) {
t.Errorf("the refusal names neither the instance nor the setting that points at it: %v", err)
}
}
// The layering rule, from this side. The transport knows numbers, logins, HTTP
// and JSON; the domain knows none of those, and neither may reach the other.
//
// The bridge is out too, and for a reason of its own: it is the layer that
// translates between the two, so it sits ABOVE both. A transport that imported
// it would be a transport that knows what an issue is, one indirection later —
// and the protocol both of them share, internal/wire, exists precisely so that
// neither has to reach for the other to name a payload.
// and the vocabulary both of them share, the SDK's payloads, exists precisely
// so that neither has to reach for the other to name one.
func TestTransportDoesNotImportTheDomain(t *testing.T) {
out, err := exec.Command("go", "list", "-deps", ".").Output()
if err != nil {
+147 -80
View File
@@ -3,10 +3,11 @@ package gitea
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
sdk "code.gitea.io/sdk/gitea"
"git.noodles.cam/claude-skills/marketplace/cli/internal/wire"
)
@@ -14,86 +15,98 @@ import (
//
// A number is an address, not a query: this answers for a closed issue exactly
// as it does for an open one.
func (c *Client) GetIssue(number int) (*wire.Issue, error) {
var got wire.Issue
if err := c.Call(http.MethodGet, c.repoPathf("issues/%d", number), nil, &got); err != nil {
func (c *Client) GetIssue(number int) (*sdk.Issue, error) {
owner, repo := c.owned()
got, resp, err := c.api.GetIssue(owner, repo, int64(number))
if err := fail(resp, err); err != nil {
return nil, err
}
// A 200 that carries no number is not this issue. Gitea has answered that
// way for a repository whose issue tracker is disabled.
if got.Number == 0 {
if got == nil || got.Index == 0 {
return nil, fmt.Errorf("issue #%d not found in %s", number, c.repo)
}
return &got, nil
return got, nil
}
// CreateIssue files a new issue. name labels the request body in the
// scratchpad; the issue's slug is what makes that dump worth keeping.
func (c *Client) CreateIssue(req wire.IssueRequest, name string) (*wire.Issue, error) {
var got wire.Issue
body := &Body{Name: name, Data: req}
if err := c.Call(http.MethodPost, c.repoPath("issues"), body, &got); err != nil {
func (c *Client) CreateIssue(opt sdk.CreateIssueOption, name string) (*sdk.Issue, error) {
owner, repo := c.owned()
c.dump.label(name)
got, resp, err := c.api.CreateIssue(owner, repo, opt)
if err := fail(resp, err); err != nil {
return nil, err
}
return &got, nil
return got, nil
}
// EditIssue patches an existing issue. Only the fields set on req are sent.
func (c *Client) EditIssue(number int, req wire.IssueRequest, name string) (*wire.Issue, error) {
var got wire.Issue
body := &Body{Name: name, Data: req}
if err := c.Call(http.MethodPatch, c.repoPathf("issues/%d", number), body, &got); err != nil {
// EditIssue patches an existing issue. Only the fields set on opt are sent.
//
// LABELS DO NOT GO THROUGH HERE. Gitea's edit endpoint takes no label list and
// neither does the SDK's EditIssueOption, so an issue whose labels changed
// needs SetLabels after this — push does exactly that, and says so.
func (c *Client) EditIssue(number int, opt sdk.EditIssueOption, name string) (*sdk.Issue, error) {
owner, repo := c.owned()
c.dump.label(name)
got, resp, err := c.api.EditIssue(owner, repo, int64(number), opt)
if err := fail(resp, err); err != nil {
return nil, err
}
return &got, nil
return got, nil
}
// SetLabels replaces an issue's labels with exactly these ids.
//
// It exists because Gitea occasionally drops labels handed to it on create, and
// the answer to that is to re-apply them rather than to trust the echo.
func (c *Client) SetLabels(number int, ids []int64, name string) ([]wire.Label, error) {
// the answer to that is to re-apply them rather than to trust the echo. It is
// also the only way to change the labels of an issue that already exists — see
// EditIssue.
func (c *Client) SetLabels(number int, ids []int64, name string) ([]*sdk.Label, error) {
if ids == nil {
ids = []int64{}
}
var got []wire.Label
body := &Body{Name: name, Data: struct {
Labels []int64 `json:"labels"`
}{ids}}
if err := c.Call(http.MethodPut, c.repoPathf("issues/%d/labels", number), body, &got); err != nil {
owner, repo := c.owned()
c.dump.label(name)
got, resp, err := c.api.ReplaceIssueLabels(owner, repo, int64(number), sdk.IssueLabelsOption{Labels: ids})
if err := fail(resp, err); err != nil {
return nil, err
}
return got, nil
}
// ListComments is an issue's whole thread, every page of it.
func (c *Client) ListComments(number int) ([]wire.Comment, error) {
return paginate[wire.Comment](c, c.repoPathf("issues/%d/comments", number), pageLimit)
func (c *Client) ListComments(number int) ([]*sdk.Comment, error) {
owner, repo := c.owned()
return paginate(func(page, limit int) ([]*sdk.Comment, error) {
got, resp, err := c.api.ListIssueComments(owner, repo, int64(number),
sdk.ListIssueCommentOptions{ListOptions: listOptions(page, limit)})
return got, fail(resp, err)
}, pageLimit)
}
// CreateComment posts a comment on an issue.
func (c *Client) CreateComment(number int, text, name string) (*wire.Comment, error) {
var got wire.Comment
body := &Body{Name: name, Data: commentBody{Body: text}}
if err := c.Call(http.MethodPost, c.repoPathf("issues/%d/comments", number), body, &got); err != nil {
func (c *Client) CreateComment(number int, text, name string) (*sdk.Comment, error) {
owner, repo := c.owned()
c.dump.label(name)
got, resp, err := c.api.CreateIssueComment(owner, repo, int64(number),
sdk.CreateIssueCommentOption{Body: text})
if err := fail(resp, err); err != nil {
return nil, err
}
return &got, nil
return got, nil
}
// EditComment rewrites one comment, addressed by its own id and not by the
// issue it is on — which is how Gitea addresses it.
func (c *Client) EditComment(id int64, text, name string) (*wire.Comment, error) {
var got wire.Comment
body := &Body{Name: name, Data: commentBody{Body: text}}
if err := c.Call(http.MethodPatch, c.repoPathf("issues/comments/%d", id), body, &got); err != nil {
func (c *Client) EditComment(id int64, text, name string) (*sdk.Comment, error) {
owner, repo := c.owned()
c.dump.label(name)
got, resp, err := c.api.EditIssueComment(owner, repo, id, sdk.EditIssueCommentOption{Body: text})
if err := fail(resp, err); err != nil {
return nil, err
}
return &got, nil
}
type commentBody struct {
Body string `json:"body"`
return got, nil
}
// --------------------------------------------------------------------------
@@ -121,13 +134,13 @@ type IssueFilter struct {
// something to say about them ("11 closed, not stored") still can.
//
// What Keep means is the caller's business; this package only counts.
Keep func(*wire.Issue) bool
Keep func(*sdk.Issue) bool
}
// IssueListing is what a filtered read found.
type IssueListing struct {
// Issues are every payload that passed the filter, kept or not.
Issues []wire.Issue
Issues []*sdk.Issue
// Milestone is the resolved milestone title, for a receipt.
Milestone string
// Warning is set when a Keep-bounded read ran out of page budget with the
@@ -167,23 +180,27 @@ func (c *Client) ListIssues(f IssueFilter) (*IssueListing, error) {
milestoneID, out.Milestone = ms.ID, ms.Title
}
params := url.Values{}
state := f.State
if state == "" {
state = "open"
}
params.Set("state", state)
params.Set("type", "issues")
if len(f.Labels) > 0 {
params.Set("labels", strings.Join(f.Labels, ","))
owner, repo := c.owned()
fetch := func(page, limit int) ([]*sdk.Issue, error) {
opt := sdk.ListIssueOption{
ListOptions: listOptions(page, limit),
State: sdk.StateType(state),
// Issues and not pull requests. The server has been known to
// ignore this, which is why matches re-checks it.
Type: sdk.IssueTypeIssue,
Labels: f.Labels,
KeyWord: f.Query,
}
if out.Milestone != "" {
opt.Milestones = []string{out.Milestone}
}
got, resp, err := c.api.ListRepoIssues(owner, repo, opt)
return got, fail(resp, err)
}
if f.Query != "" {
params.Set("q", f.Query)
}
if out.Milestone != "" {
params.Set("milestones", out.Milestone)
}
path := c.repoPath("issues?" + params.Encode())
perPage := min(f.Limit, pageLimit)
ideal := max(1, (f.Limit+perPage-1)/perPage)
@@ -193,15 +210,14 @@ func (c *Client) ListIssues(f IssueFilter) (*IssueListing, error) {
}
kept, seen, lastFull := 0, 0, false
err := pages(c, path, perPage, budget, func(batch []wire.Issue) (bool, error) {
err := pages(fetch, perPage, budget, func(batch []*sdk.Issue) (bool, error) {
seen++
lastFull = len(batch) == perPage
for i := range batch {
p := &batch[i]
for _, p := range batch {
if !matches(p, milestoneID, f.Labels) {
continue
}
out.Issues = append(out.Issues, *p)
out.Issues = append(out.Issues, p)
if f.Keep == nil || f.Keep(p) {
kept++
if kept >= f.Limit {
@@ -230,10 +246,10 @@ func (c *Client) ListIssues(f IssueFilter) (*IssueListing, error) {
// matters most — a pull request rendered as a unit of work is not a bug the
// operator can see until it is in the store.
//
// A function and not a method: the payload is the protocol's, and re-checking a
// filter the server ignored is this package's business, not the protocol's.
func matches(i *wire.Issue, milestoneID int64, labels []string) bool {
if i.IsPullRequest() {
// A function and not a method: the payload is the SDK's, and re-checking a
// filter the server ignored is this package's business, not the payload's.
func matches(i *sdk.Issue, milestoneID int64, labels []string) bool {
if i.PullRequest != nil {
return false
}
if milestoneID != 0 && (i.Milestone == nil || i.Milestone.ID != milestoneID) {
@@ -255,28 +271,46 @@ func matches(i *wire.Issue, milestoneID int64, labels []string) bool {
// dependencies
// --------------------------------------------------------------------------
// issueMeta is Gitea's IssueMeta: how a dependency names another issue.
type issueMeta struct {
Index int `json:"index"`
Owner string `json:"owner"`
Repo string `json:"repo"`
// dependenciesSince is the first Gitea release that answers at
// /issues/{index}/dependencies at all.
//
// Checked against the release tags themselves and not guessed: the routes are
// absent from routers/api/v1/api.go through 1.19 and present in 1.20. Asking
// the version rather than the endpoint is what turns "some error came back"
// into an answer — and it costs no request, because the SDK already negotiated
// the version when the client was built.
const dependenciesSince = ">= 1.20.0"
// hasDependencies reports whether this instance is new enough to have the
// dependency endpoints.
func (c *Client) hasDependencies() bool {
return c.api.CheckServerVersionConstraint(dependenciesSince) == nil
}
// Dependencies are the issues that block this one — Gitea's own dependency
// links, read in the direction AddDependency writes them.
//
// An instance that does not have the endpoint, or has dependencies turned off
// for this repository, answers with a status rather than a list. That is
// reported as "no dependencies" and not as a failure: a pull must still bring
// the issue itself back from a tracker whose dependency support is off.
// TWO WAYS FOR THERE TO BE NO ANSWER, and both are reported as "no
// dependencies" rather than as a failure, because a pull must still bring the
// issue itself back:
//
// - the instance predates the endpoint, which the version says before a
// request is made;
// - the instance has it but this repository does not — dependencies turned
// off, a tracker disabled — which only the tracker's own answer can say.
//
// Deliberately narrower than the Python it replaces, which swallowed every
// failure here including a dead connection. "The server said no" and "there was
// no server" are different answers, and only the first one means the feature is
// missing.
func (c *Client) Dependencies(number int) ([]wire.Issue, error) {
var got []wire.Issue
err := c.Call(http.MethodGet, c.repoPathf("issues/%d/dependencies", number), nil, &got)
func (c *Client) Dependencies(number int) ([]*sdk.Issue, error) {
if !c.hasDependencies() {
return nil, nil
}
owner, repo := c.owned()
got, resp, err := c.api.ListIssueDependencies(owner, repo, int64(number),
sdk.ListIssueDependenciesOptions{ListOptions: listOptions(1, pageLimit)})
err = fail(resp, err)
var apiErr *APIError
if errors.As(err, &apiErr) {
return nil, nil
@@ -298,12 +332,38 @@ func (c *Client) DependencyKeys(number int) ([]wire.Key, error) {
return nil, err
}
out := make([]wire.Key, 0, len(deps))
for i := range deps {
out = append(out, deps[i].KeyIn(c.repo))
for _, d := range deps {
out = append(out, keyIn(d, c.repo))
}
return out, nil
}
// keyIn is a payload's cross-repo handle. The payload's own repository wins
// when it carries one — a dependency listing answers with issues from other
// repositories — and fallback is the repository that was asked.
func keyIn(p *sdk.Issue, fallback wire.Repo) wire.Key {
repo := fallback
if p.Repository != nil {
if r, err := wire.ParseRepo(p.Repository.FullName); err == nil {
repo = r
}
}
return wire.Key{Repo: repo, Number: int(p.Index)}
}
// issueMeta is Gitea's own IssueMeta: how a dependency names another issue.
//
// The SDK has a type of this name too and it carries only `index`, so it can
// only ever link inside one repository. Gitea's has taken an owner and a repo
// since the endpoint existed, and a `depends:` entry is allowed to live
// somewhere else — so this one struct and the raw POST that sends it are all
// that is left of the hand-rolled client.
type issueMeta struct {
Index int `json:"index"`
Owner string `json:"owner"`
Repo string `json:"repo"`
}
// AddDependency makes issue number depend on dep.
//
// Confirmed against an instance's own swagger.v1.json (Gitea 1.26.1):
@@ -324,9 +384,16 @@ func (c *Client) AddDependency(number int, dep wire.Key) error {
if dep.Number < 1 {
return fmt.Errorf("dependency %s names no issue number", dep)
}
body := &Body{
Name: fmt.Sprintf("dep-%d-%d", number, dep.Number),
Data: issueMeta{Index: dep.Number, Owner: dep.Repo.Owner, Repo: dep.Repo.Name},
if !c.hasDependencies() {
return fmt.Errorf("this Gitea has no issue-dependency API (it is not %s) — link #%d -> %s by hand",
strings.TrimPrefix(dependenciesSince, ">= "), number, dep)
}
return c.Call(http.MethodPost, c.repoPathf("issues/%d/dependencies", number), body, nil)
// Owner and name are escaped, the way the SDK escapes them for every other
// call: they arrive from a config file, and a file is a thing people type
// into.
return c.post(
fmt.Sprintf("repos/%s/%s/issues/%d/dependencies",
url.PathEscape(c.repo.Owner), url.PathEscape(c.repo.Name), number),
issueMeta{Index: dep.Number, Owner: dep.Repo.Owner, Repo: dep.Repo.Name},
fmt.Sprintf("dep-%d-%d", number, dep.Number))
}
+56 -26
View File
@@ -2,11 +2,10 @@ package gitea
import (
"fmt"
"net/http"
"strconv"
"strings"
"git.noodles.cam/claude-skills/marketplace/cli/internal/wire"
sdk "code.gitea.io/sdk/gitea"
)
// ListLabels is every label in the repository, every page of it.
@@ -14,8 +13,13 @@ import (
// A bootstrap decides its plan against this and never against a cache: a cache
// answers "what did we create last time", and the question is "what does the
// repository have right now".
func (c *Client) ListLabels() ([]wire.Label, error) {
return paginate[wire.Label](c, c.repoPath("labels"), 100)
func (c *Client) ListLabels() ([]*sdk.Label, error) {
owner, repo := c.owned()
return paginate(func(page, limit int) ([]*sdk.Label, error) {
got, resp, err := c.api.ListRepoLabels(owner, repo,
sdk.ListLabelsOptions{ListOptions: listOptions(page, limit)})
return got, fail(resp, err)
}, 100)
}
// CreateLabel adds a label to the repository.
@@ -26,26 +30,40 @@ func (c *Client) ListLabels() ([]wire.Label, error) {
//
// What a label MEANS is not decided here either: this creates what it is
// handed.
func (c *Client) CreateLabel(req wire.LabelRequest) (*wire.Label, error) {
var got wire.Label
body := &Body{Name: "label-" + req.Name, Data: req}
if err := c.Call(http.MethodPost, c.repoPath("labels"), body, &got); err != nil {
func (c *Client) CreateLabel(opt sdk.CreateLabelOption) (*sdk.Label, error) {
owner, repo := c.owned()
c.dump.label("label-" + opt.Name)
got, resp, err := c.api.CreateLabel(owner, repo, opt)
if err := fail(resp, err); err != nil {
return nil, err
}
if got.ID == 0 {
return nil, fmt.Errorf("creating label %q: the tracker's answer carries no id", req.Name)
if got == nil || got.ID == 0 {
return nil, fmt.Errorf("creating label %q: the tracker's answer carries no id", opt.Name)
}
return &got, nil
return got, nil
}
// EditLabel patches an existing label by id.
func (c *Client) EditLabel(id int64, req wire.LabelRequest) (*wire.Label, error) {
var got wire.Label
body := &Body{Name: "label-" + req.Name, Data: req}
if err := c.Call(http.MethodPatch, c.repoPathf("labels/%d", id), body, &got); err != nil {
//
// It takes the same spec a create takes, and sends every field of it. The SDK
// spells an edit with pointers, where nil means "leave it alone" — but a label
// edit is rare enough that sending the unchanged name and description along
// costs nothing and removes a way to lose them on a server that reads an absent
// field as empty. The caller decides what the label should BE; this makes the
// tracker say that and nothing less.
func (c *Client) EditLabel(id int64, opt sdk.CreateLabelOption) (*sdk.Label, error) {
owner, repo := c.owned()
c.dump.label("label-" + opt.Name)
got, resp, err := c.api.EditLabel(owner, repo, id, sdk.EditLabelOption{
Name: &opt.Name,
Color: &opt.Color,
Description: &opt.Description,
Exclusive: &opt.Exclusive,
})
if err := fail(resp, err); err != nil {
return nil, err
}
return &got, nil
return got, nil
}
// ListMilestones is every milestone in the repository, open and closed.
@@ -53,8 +71,15 @@ func (c *Client) EditLabel(id int64, req wire.LabelRequest) (*wire.Label, error)
// Both states, always: a milestone is closed the moment its work is done, and a
// listing that hid those would fail to resolve exactly the filter somebody
// types when they want to see what was in it.
func (c *Client) ListMilestones() ([]wire.Milestone, error) {
return paginate[wire.Milestone](c, c.repoPath("milestones?state=all"), 100)
func (c *Client) ListMilestones() ([]*sdk.Milestone, error) {
owner, repo := c.owned()
return paginate(func(page, limit int) ([]*sdk.Milestone, error) {
got, resp, err := c.api.ListRepoMilestones(owner, repo, sdk.ListMilestoneOption{
ListOptions: listOptions(page, limit),
State: sdk.StateAll,
})
return got, fail(resp, err)
}, 100)
}
// ResolveMilestone finds a milestone by id or by title, and fails when there is
@@ -64,14 +89,19 @@ func (c *Client) ListMilestones() ([]wire.Milestone, error) {
// Gitea silently ignores a `milestones=` filter it cannot resolve and answers
// with the entire backlog. A typo in a milestone name would otherwise read as
// "your milestone has 300 issues in it".
func (c *Client) ResolveMilestone(value string) (*wire.Milestone, error) {
//
// Against the whole listing rather than the SDK's GetMilestoneByName, because a
// failure has to say what the repository actually HAS — and because that helper
// matches case-insensitively, which would resolve two different milestones to
// one on a repository that has both.
func (c *Client) ResolveMilestone(value string) (*sdk.Milestone, error) {
got, err := c.ListMilestones()
if err != nil {
return nil, err
}
for i := range got {
if got[i].Title == value || strconv.FormatInt(got[i].ID, 10) == value {
return &got[i], nil
for _, m := range got {
if m.Title == value || strconv.FormatInt(m.ID, 10) == value {
return m, nil
}
}
have := make([]string, 0, len(got))
@@ -91,7 +121,7 @@ func (c *Client) ResolveMilestone(value string) (*wire.Milestone, error) {
// milestone the tracker does not have is filed without one, because refusing
// the whole push over a field the tracker will happily accept as empty helps
// nobody. "none" and "" are both "no milestone".
func (c *Client) FindMilestone(title string) (*wire.Milestone, error) {
func (c *Client) FindMilestone(title string) (*sdk.Milestone, error) {
if title == "" || title == "none" {
return nil, nil
}
@@ -99,9 +129,9 @@ func (c *Client) FindMilestone(title string) (*wire.Milestone, error) {
if err != nil {
return nil, err
}
for i := range got {
if got[i].Title == title {
return &got[i], nil
for _, m := range got {
if m.Title == title {
return m, nil
}
}
return nil, nil