From edd05aea6b195173551810bc8c5ed4ec2d08fdf8 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 22 Jul 2026 05:15:09 +1000 Subject: [PATCH] feat: add Gitea forge support alongside GitHub MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the Forge interface for Gitea instances (tested against git.catlow.cloud, Gitea v1.26.4). The forge.New factory now dispatches on forge type, and config validation accepts 'gitea'. Changes: - internal/forge/gitea.go — GiteaClient implementing all 11 Forge methods: issue polling (assigned + label), comments, PR creation, PR state reconciliation, issue closure, reactions, state labels, push verification. Handles edge cases: not-found PRs return 'closed', GetUserByName errors from the Gitea SDK are mapped to user-friendly messages. - internal/forge/forge.go — New() factory dispatching on forge type (github/gitea). GitHub constructor renamed to NewGitHub. - internal/forge/github_test.go — updated to use New() signature - internal/config/config.go — forge.type accepts 'gitea', BotEmail defaults change per forge type (gitea uses @gitea.local) - cmd/archied/main.go — passes cfg.Forge.Type to forge.New() Dependencies: added code.gitea.io/sdk/gitea v0.25.1 End-to-end verified against live Gitea instance: daemon starts clean, registry built (5 workflows), web UI listening, no errors or warnings. --- cmd/archied/main.go | 2 +- go.mod | 5 + go.sum | 23 +++ internal/config/config.go | 15 +- internal/forge/forge.go | 21 ++- internal/forge/gitea.go | 309 ++++++++++++++++++++++++++++++++++ internal/forge/github.go | 6 +- internal/forge/github_test.go | 2 +- 8 files changed, 371 insertions(+), 12 deletions(-) create mode 100644 internal/forge/gitea.go diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 4d78fbaa6..2c0bad0c6 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -57,7 +57,7 @@ func run() int { fmt.Fprintln(os.Stderr, cfg.Forge.TokenEnv+" is required") return 1 } - forgeClient, err := forge.New(token, cfg.Forge.Host, log) + forgeClient, err := forge.New(cfg.Forge.Type, token, cfg.Forge.Host, log) if err != nil { fmt.Fprintln(os.Stderr, err) return 1 diff --git a/go.mod b/go.mod index 4fd7e0c6b..d658054d6 100644 --- a/go.mod +++ b/go.mod @@ -9,20 +9,25 @@ require ( ) require ( + code.gitea.io/sdk/gitea v0.25.1 // indirect + github.com/42wim/httpsig v1.2.4 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect github.com/containerd/errdefs v1.0.0 // indirect github.com/containerd/errdefs/pkg v0.3.0 // indirect + github.com/davidmz/go-pageant v1.0.2 // indirect github.com/distribution/reference v0.6.0 // indirect github.com/docker/go-connections v0.7.0 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/go-fed/httpsig v1.1.0 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/go-tpm v0.9.8 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/go-version v1.9.0 // indirect github.com/klauspost/compress v1.18.6 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/minio/highwayhash v1.0.4 // indirect diff --git a/go.sum b/go.sum index 1e331b80a..e573d952e 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,7 @@ +code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE= +code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg= +github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU= +github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= @@ -10,6 +14,8 @@ github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151X github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0= +github.com/davidmz/go-pageant v1.0.2/go.mod h1:P2EDDnMqIwG5Rrp05dTRITj9z2zpGcD9efWSkTNKLIE= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= @@ -20,6 +26,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI= +github.com/go-fed/httpsig v1.1.0/go.mod h1:RCMrTZvN1bJYtofsG4rd5NaO5obxQ5xBkdiS7xsT7bM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -38,6 +46,8 @@ github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17k github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA= +github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao= @@ -84,6 +94,7 @@ github.com/samcharles93/ai-sdk v0.1.17 h1:yH48jrYVyFv+VO1qYkbReVpVxP063XMs0T/Jb9 github.com/samcharles93/ai-sdk v0.1.17/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E= github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= @@ -100,19 +111,31 @@ go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5J go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w= go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/config/config.go b/internal/config/config.go index f5f833d2b..29e66fb6c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -376,14 +376,21 @@ func Load(path string) (Config, error) { if cfg.BotUser == "" { return cfg, errors.New("config: bot_user is required") } - if cfg.BotEmail == "" && cfg.Forge.Type == "github" { - cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com" + if cfg.BotEmail == "" { + switch cfg.Forge.Type { + case "github": + cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com" + case "gitea": + cfg.BotEmail = cfg.BotUser + "@gitea.local" + } } if len(cfg.Repos) == 0 { return cfg, errors.New("config: at least one [[repos]] entry is required") } - if cfg.Forge.Type != "github" { - return cfg, fmt.Errorf("config: forge.type %q is not yet supported", cfg.Forge.Type) + switch cfg.Forge.Type { + case "github", "gitea": + default: + return cfg, fmt.Errorf("config: forge.type %q is not supported (want github or gitea)", cfg.Forge.Type) } for i, r := range cfg.Repos { if r.Owner == "" || r.Name == "" { diff --git a/internal/forge/forge.go b/internal/forge/forge.go index dcc5be360..5b129fc58 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -1,10 +1,25 @@ // Package forge defines the interface archie uses to interact with a git // host — polling issues, managing labels, opening PRs, and reacting to -// comments. GitHub is the primary implementation; other hosts (Gitea, -// GitLab) can be added later by implementing this interface. +// comments. GitHub and Gitea are the supported implementations. package forge -import "context" +import ( + "context" + "fmt" + "log/slog" +) + +// New creates a Forge implementation for the given type. +func New(forgeType, token, host string, log *slog.Logger) (Forge, error) { + switch forgeType { + case "github": + return NewGitHub(token, host, log) + case "gitea": + return NewGitea(token, host, log) + default: + return nil, fmt.Errorf("unsupported forge type %q (want github or gitea)", forgeType) + } +} // Issue is a forge-neutral representation of an issue (not a PR). type Issue struct { diff --git a/internal/forge/gitea.go b/internal/forge/gitea.go new file mode 100644 index 000000000..d7f2bcf0b --- /dev/null +++ b/internal/forge/gitea.go @@ -0,0 +1,309 @@ +package forge + +import ( + "context" + "fmt" + "log/slog" + "strings" + "sync" + + "code.gitea.io/sdk/gitea" +) + +// GiteaClient implements Forge against a Gitea instance. +type GiteaClient struct { + cli *gitea.Client + log *slog.Logger + + labelMu sync.Mutex + labelsEnsured map[string]bool +} + +// NewGitea creates a Gitea-backed Forge implementation. +func NewGitea(token, host string, log *slog.Logger) (Forge, error) { + host = strings.TrimRight(host, "/") + cli, err := gitea.NewClient(host, gitea.SetToken(token)) + if err != nil { + return nil, fmt.Errorf("gitea client %s: %w", host, err) + } + return &GiteaClient{cli: cli, log: log}, nil +} + +// ── Forge interface ────────────────────────────────────────────────── + +// AcceptInvitations auto-accepts pending repository invitations. +func (c *GiteaClient) AcceptInvitations(ctx context.Context) error { + // Gitea doesn't have a direct equivalent to GitHub's user invitations + // API. Repository collaborators are added directly by the owner. + return nil +} + +// AssignedIssues returns open issues assigned to the given user, excluding PRs. +func (c *GiteaClient) AssignedIssues(ctx context.Context, owner, repo, assignee string) ([]Issue, error) { + opts := gitea.ListIssueOption{ + ListOptions: gitea.ListOptions{PageSize: 50}, + State: gitea.StateOpen, + AssignedBy: assignee, + } + var out []Issue + for { + issues, resp, err := c.cli.ListRepoIssues(owner, repo, opts) + if err != nil { + return nil, fmt.Errorf("list issues %s/%s: %w", owner, repo, err) + } + for _, is := range issues { + if is.PullRequest == nil { + out = append(out, Issue{ + Number: int(is.Index), + Title: is.Title, + Body: is.Body, + Labels: labelNamesGitea(is.Labels), + }) + } + } + if resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + return out, nil +} + +// IssuesWithLabel returns open issues matching the given label, excluding PRs. +func (c *GiteaClient) IssuesWithLabel(ctx context.Context, owner, repo, label string) ([]Issue, error) { + opts := gitea.ListIssueOption{ + ListOptions: gitea.ListOptions{PageSize: 50}, + State: gitea.StateOpen, + Labels: []string{label}, + } + var out []Issue + for { + issues, resp, err := c.cli.ListRepoIssues(owner, repo, opts) + if err != nil { + return nil, fmt.Errorf("list issues %s/%s: %w", owner, repo, err) + } + for _, is := range issues { + if is.PullRequest == nil { + out = append(out, Issue{ + Number: int(is.Index), + Title: is.Title, + Body: is.Body, + Labels: labelNamesGitea(is.Labels), + }) + } + } + if resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + return out, nil +} + +// Comment posts an issue comment and returns its id. +func (c *GiteaClient) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) { + cm, _, err := c.cli.CreateIssueComment(owner, repo, int64(number), gitea.CreateIssueCommentOption{Body: body}) + if err != nil { + return 0, err + } + return cm.ID, nil +} + +// RepliesAfter returns comments on the issue with id > afterID not written +// by exclude. +func (c *GiteaClient) RepliesAfter(ctx context.Context, owner, repo string, number int, afterID int64, exclude string) ([]Reply, error) { + comments, _, err := c.cli.ListIssueComments(owner, repo, int64(number), gitea.ListIssueCommentOptions{ + ListOptions: gitea.ListOptions{PageSize: 50}, + }) + if err != nil { + return nil, err + } + var out []Reply + for _, cm := range comments { + if cm.ID <= afterID || cm.Poster.UserName == exclude { + continue + } + out = append(out, Reply{ID: cm.ID, User: cm.Poster.UserName, Body: cm.Body}) + } + return out, nil +} + +// CreatePR opens a pull request and returns its number. +func (c *GiteaClient) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) { + pr, _, err := c.cli.CreatePullRequest(owner, repo, gitea.CreatePullRequestOption{ + Title: title, + Head: head, + Base: base, + Body: body, + }) + if err != nil { + return 0, fmt.Errorf("create PR %s/%s: %w", owner, repo, err) + } + return int(pr.Index), nil +} + +// PRState returns "open", "merged", or "closed" for a PR. +// Returns "closed" for non-existent PRs (already merged/closed/removed). +func (c *GiteaClient) PRState(ctx context.Context, owner, repo string, number int) (string, error) { + pr, _, err := c.cli.GetPullRequest(owner, repo, int64(number)) + if err != nil { + // "not found" means the PR was already merged/closed and cleaned up. + if strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "GetUserByName") { + return "closed", nil + } + return "", err + } + if pr.HasMerged { + return "merged", nil + } + return string(pr.State), nil +} + +// CloseIssue closes an issue with an optional final comment. +func (c *GiteaClient) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error { + if comment != "" { + if _, err := c.Comment(ctx, owner, repo, number, comment); err != nil { + return err + } + } + state := gitea.StateClosed + _, _, err := c.cli.EditIssue(owner, repo, int64(number), gitea.EditIssueOption{State: &state}) + return err +} + +// React adds an emoji reaction to an issue. +func (c *GiteaClient) React(ctx context.Context, owner, repo string, number int, reaction string) error { + _, _, err := c.cli.PostIssueReaction(owner, repo, int64(number), reaction) + return err +} + +// SetStateLabel makes label the issue's only state label. +func (c *GiteaClient) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string) { + known := make(map[string]bool, len(knownLabels)) + for _, l := range knownLabels { + known[l] = true + } + issue, _, err := c.cli.GetIssue(owner, repo, int64(number)) + if err != nil { + c.log.Warn("set state label: get issue failed", "issue", number, "err", err) + return + } + // Remove known state labels (except the target). + labelIDs := make([]int64, 0, len(issue.Labels)) + for _, l := range issue.Labels { + if l.Name == label { + label = "" // already present + labelIDs = append(labelIDs, l.ID) + } else if known[l.Name] { + if _, err := c.cli.DeleteIssueLabel(owner, repo, int64(number), l.ID); err != nil { + c.log.Warn("remove state label failed", "label", l.Name, "err", err) + } + } else { + labelIDs = append(labelIDs, l.ID) + } + } + if label == "" { + return + } + // Find or create the target label and add it by ID. + labelID := c.resolveLabelID(ctx, owner, repo, label) + if labelID == 0 { + return // ensureLabel already logged + } + if _, _, err := c.cli.AddIssueLabels(owner, repo, int64(number), gitea.IssueLabelsOption{ + Labels: []int64{labelID}, + }); err != nil { + c.log.Warn("add state label failed", "label", label, "err", err) + } +} + +// resolveLabelID returns the ID of a label, creating it if necessary. +func (c *GiteaClient) resolveLabelID(ctx context.Context, owner, repo, name string) int64 { + labels, _, err := c.cli.ListRepoLabels(owner, repo, gitea.ListLabelsOptions{ListOptions: gitea.ListOptions{PageSize: 100}}) + if err != nil { + c.log.Warn("list repo labels failed", "err", err) + return 0 + } + for _, l := range labels { + if l.Name == name { + return l.ID + } + } + // Create the label. + c.ensureLabel(ctx, owner, repo, name) + // Re-list to get the new ID. + labels, _, err = c.cli.ListRepoLabels(owner, repo, gitea.ListLabelsOptions{ListOptions: gitea.ListOptions{PageSize: 100}}) + if err != nil { + return 0 + } + for _, l := range labels { + if l.Name == name { + return l.ID + } + } + return 0 +} + +// VerifyPush confirms the token can push to the repo. +func (c *GiteaClient) VerifyPush(ctx context.Context, owner, repo string) error { + r, _, err := c.cli.GetRepo(owner, repo) + if err != nil { + // Gitea SDK may return "GetUserByName" for a non-existent repo. + if strings.Contains(err.Error(), "GetUserByName") { + return fmt.Errorf("repo %s/%s not found or token lacks access", owner, repo) + } + return fmt.Errorf("get repo %s/%s: %w", owner, repo, err) + } + if !r.Permissions.Push { + return fmt.Errorf("no push permission on %s/%s", owner, repo) + } + return nil +} + +// ── helpers ────────────────────────────────────────────────────────── + +func labelNamesGitea(labels []*gitea.Label) []string { + var names []string + for _, l := range labels { + names = append(names, l.Name) + } + return names +} + +// Gitea state label colours matching the GitHub palette. +var giteaStateLabelColors = map[string]string{ + "archie:queued": "#bfd4f2", + "archie:working": "#1d76db", + "archie:waiting": "#fbca04", + "archie:pr": "#0e8a16", + "archie:parked": "#d93f0b", +} + +func (c *GiteaClient) ensureLabel(ctx context.Context, owner, repo, name string) { + key := owner + "/" + repo + "/" + name + c.labelMu.Lock() + seen := c.labelsEnsured[key] + c.labelMu.Unlock() + if seen { + return + } + color := giteaStateLabelColors[name] + if color == "" { + color = "#bfd4f2" + } + _, _, err := c.cli.CreateLabel(owner, repo, gitea.CreateLabelOption{ + Name: name, + Color: color, + Description: "archie task state (managed automatically)", + }) + if err != nil && !strings.Contains(err.Error(), "already exists") && !strings.Contains(err.Error(), "422") { + c.log.Warn("create label failed", "label", name, "err", err) + return + } + c.labelMu.Lock() + if c.labelsEnsured == nil { + c.labelsEnsured = map[string]bool{} + } + c.labelsEnsured[key] = true + c.labelMu.Unlock() +} diff --git a/internal/forge/github.go b/internal/forge/github.go index a24491b56..2498aff5c 100644 --- a/internal/forge/github.go +++ b/internal/forge/github.go @@ -23,9 +23,9 @@ type GitHubClient struct { labelsEnsured map[string]bool } -// New creates a GitHub-backed Forge implementation. Non-github.com hosts -// are configured using GitHub Enterprise's API and upload URL conventions. -func New(token, host string, log *slog.Logger) (Forge, error) { +// NewGitHub creates a GitHub-backed Forge implementation. Non-github.com +// hosts are configured using GitHub Enterprise's API and upload URL conventions. +func NewGitHub(token, host string, log *slog.Logger) (Forge, error) { client := github.NewClient(nil) if strings.TrimRight(host, "/") != "https://github.com" { var err error diff --git a/internal/forge/github_test.go b/internal/forge/github_test.go index 17ac3b3e3..d8e7b1a10 100644 --- a/internal/forge/github_test.go +++ b/internal/forge/github_test.go @@ -29,7 +29,7 @@ func TestNewConfiguresHost(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - f, err := New("token", tt.host, slog.New(slog.NewTextHandler(io.Discard, nil))) + f, err := New("github", "token", tt.host, slog.New(slog.NewTextHandler(io.Discard, nil))) if err != nil { t.Fatal(err) }