diff --git a/internal/cli/forge_client.go b/internal/cli/forge_client.go index 27b741f7e0..728b2de14d 100644 --- a/internal/cli/forge_client.go +++ b/internal/cli/forge_client.go @@ -7,12 +7,14 @@ import ( "sync" "github.com/fullsend-ai/fullsend/internal/forge" + fj "github.com/fullsend-ai/fullsend/internal/forge/forgejo" gl "github.com/fullsend-ai/fullsend/internal/forge/gitlab" "github.com/fullsend-ai/fullsend/internal/repos" "github.com/spf13/cobra" ) var errGitLabTokenMissing = errors.New("no GitLab token found: set GITLAB_TOKEN or pass --gitlab-token") +var errForgejoTokenMissing = errors.New("no Forgejo token found: set FORGEJO_TOKEN or GITEA_TOKEN") // resolveGitLabToken returns a GitLab personal or project access token // from the environment. Unlike GitHub tokens, there is no `glab auth @@ -24,15 +26,28 @@ func resolveGitLabToken() (string, error) { return "", errGitLabTokenMissing } +// resolveForgejoToken returns a Forgejo/Gitea access token from the +// environment (FORGEJO_TOKEN preferred, then GITEA_TOKEN). +func resolveForgejoToken() (string, error) { + if token := os.Getenv("FORGEJO_TOKEN"); token != "" { + return token, nil + } + if token := os.Getenv("GITEA_TOKEN"); token != "" { + return token, nil + } + return "", errForgejoTokenMissing +} + // newForgeClient creates a forge.Client for the given forge type. // For GitHub, it delegates to newAuthenticatedGitHubClient (GH_TOKEN, // GITHUB_TOKEN, gh auth token). For GitLab, it uses GITLAB_TOKEN or -// the provided gitlabToken override. +// the provided gitlabToken override. For Forgejo, it uses FORGEJO_TOKEN +// or GITEA_TOKEN (gitlabToken override is ignored). // // The baseURL parameter, when non-empty, sets the forge instance URL // (from the manifest's forge section). It takes precedence over the -// GITLAB_API_URL / GITHUB_API_URL environment variables, which are -// kept as a fallback for callers that don't have a manifest yet. +// GITLAB_API_URL / GITHUB_API_URL / FORGEJO_API_URL environment variables, +// which are kept as a fallback for callers that don't have a manifest yet. func newForgeClient(forgeName, gitlabToken, baseURL string, glOpts ...gl.Option) (forge.Client, error) { switch forgeName { case repos.ForgeGitLab: @@ -54,6 +69,24 @@ func newForgeClient(forgeName, gitlabToken, baseURL string, glOpts ...gl.Option) } opts = append(opts, glOpts...) return gl.New(token, opts...) + case repos.ForgeForgejo: + token, err := resolveForgejoToken() + if err != nil { + return nil, err + } + var opts []fj.Option + raw := baseURL + if raw == "" { + raw = os.Getenv("FORGEJO_API_URL") + } + if raw == "" { + raw = os.Getenv("GITEA_API_URL") + } + if raw == "" { + return nil, fmt.Errorf("forgejo API URL required: set FORGEJO_API_URL or GITEA_API_URL, or pass a manifest URL") + } + opts = append(opts, fj.WithBaseURL(raw)) + return fj.New(token, opts...), nil case repos.ForgeGitHub, "": return newAuthenticatedGitHubClient("", baseURL) default: diff --git a/internal/cli/forge_client_test.go b/internal/cli/forge_client_test.go index 163983d5e7..17aae054c4 100644 --- a/internal/cli/forge_client_test.go +++ b/internal/cli/forge_client_test.go @@ -3,6 +3,7 @@ package cli import ( "testing" + fj "github.com/fullsend-ai/fullsend/internal/forge/forgejo" gl "github.com/fullsend-ai/fullsend/internal/forge/gitlab" "github.com/fullsend-ai/fullsend/internal/repos" "github.com/spf13/cobra" @@ -102,6 +103,34 @@ func TestNewForgeClient_Unsupported(t *testing.T) { assert.Contains(t, err.Error(), "unsupported forge") } +func TestNewForgeClient_Forgejo_FromEnv(t *testing.T) { + t.Setenv("FORGEJO_TOKEN", "fj-test-token") + t.Setenv("GITEA_TOKEN", "") + client, err := newForgeClient(repos.ForgeForgejo, "", "https://git.forge.internal") + require.NoError(t, err) + require.NotNil(t, client) + fjClient, ok := client.(*fj.LiveClient) + require.True(t, ok) + assert.Equal(t, "https://git.forge.internal/api/v1", fjClient.BaseURL()) +} + +func TestNewForgeClient_Forgejo_NoToken(t *testing.T) { + t.Setenv("FORGEJO_TOKEN", "") + t.Setenv("GITEA_TOKEN", "") + _, err := newForgeClient(repos.ForgeForgejo, "", "") + require.Error(t, err) + assert.Contains(t, err.Error(), "no Forgejo token found") +} + +func TestNewForgeClient_Forgejo_RequiresURL(t *testing.T) { + t.Setenv("FORGEJO_TOKEN", "fj-test-token") + t.Setenv("FORGEJO_API_URL", "") + t.Setenv("GITEA_API_URL", "") + _, err := newForgeClient(repos.ForgeForgejo, "", "") + require.Error(t, err) + assert.Contains(t, err.Error(), "forgejo API URL required") +} + func TestNewForgeClientFactory_GitHub(t *testing.T) { t.Setenv("GH_TOKEN", "ghp-test-token") factory := newForgeClientFactory("", nil) diff --git a/internal/cli/run.go b/internal/cli/run.go index e3ba55d7bf..d04665c41f 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -1047,6 +1047,12 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep if roleErr := applyGitLabAgentCredentials(agentName, h.Role, os.Getenv, setFlagEnv, printer); roleErr != nil { return roleErr } + } else if forgePlatform == repos.ForgeForgejo { + // Forgejo has no GitHub App mint endpoint; use FORGEJO_TOKEN / GITEA_TOKEN directly. + mintCleanup = func() {} + if mintURL != "" { + printer.StepWarn("mint_url is ignored for forgejo; using FORGEJO_TOKEN/GITEA_TOKEN") + } } else { var mintErr error minted, mintCleanup, mintErr = mintAgentTokenAtLevel(ctx, h.Role, mintURL, forgePlatform, runtimeLevel, printer) @@ -7066,6 +7072,9 @@ func setupStatusNotifier(fullsendDir string, role string, forgePlatform string, if forgePlatform == "gitlab" { return setupStatusNotifierGitLab(notifyCfg, owner, repo, sOpts, printer) } + if forgePlatform == repos.ForgeForgejo { + return nil, fmt.Errorf("status notifications are not supported for forgejo yet") + } return setupStatusNotifierGitHub(notifyCfg, fsCfg, owner, repo, role, sOpts, printer) } @@ -7471,7 +7480,7 @@ var roleTokenVars = map[string][]tokenVar{ // the function, instead of at the call site, also means a test can pass // an already-cancelled ctx directly and still observe the remint run. func remintAgentTokenForPostScript(ctx context.Context, h *harness.Harness, mintURL, forgePlatform, currentLevel string, printer *ui.Printer) (func(), error) { - if forgePlatform == "gitlab" || mintURL == "" { + if forgePlatform == "gitlab" || forgePlatform == repos.ForgeForgejo || mintURL == "" { return func() {}, nil } remintCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), remintForPostScriptTimeout) @@ -7540,7 +7549,7 @@ func syncRunnerEnvTokens(h *harness.Harness) { // No-op when levels match, mintURL is empty, or the forge is GitLab. func maybeRemintAgentTokenForStage(ctx context.Context, h *harness.Harness, mintURL, forgePlatform, stage, currentLevel string, printer *ui.Printer) (func(), error) { noop := func() {} - if h == nil || mintURL == "" || forgePlatform == "gitlab" { + if h == nil || mintURL == "" || forgePlatform == "gitlab" || forgePlatform == repos.ForgeForgejo { return noop, nil } level := h.PrivilegeLevelForStage(stage) diff --git a/internal/forge/detect.go b/internal/forge/detect.go index 33bdc8dfb6..6d9bc33b66 100644 --- a/internal/forge/detect.go +++ b/internal/forge/detect.go @@ -7,7 +7,7 @@ import ( ) // DetectForge identifies which forge platform a git remote URL points to. -// Returns "github" or "gitlab". Returns an error for unknown hosts +// Returns "github", "gitlab", or "forgejo". Returns an error for unknown hosts // with a suggestion to use the --forge flag. // // Note: this detects the forge from a remote URL, which is distinct from @@ -25,7 +25,13 @@ func DetectForge(remoteURL string) (string, error) { return "github", nil case "gitlab.com": return "gitlab", nil + case "codeberg.org", "gitea.com": + return "forgejo", nil default: + // Common self-hosted Forgejo/Gitea hostnames. + if strings.Contains(strings.ToLower(host), "forgejo") || strings.Contains(strings.ToLower(host), "gitea") { + return "forgejo", nil + } return "", fmt.Errorf("unknown forge host %q: use --forge flag for self-hosted instances", host) } } diff --git a/internal/forge/detect_test.go b/internal/forge/detect_test.go index 39d1dd111c..06eb01f862 100644 --- a/internal/forge/detect_test.go +++ b/internal/forge/detect_test.go @@ -32,6 +32,16 @@ func TestDetectForge(t *testing.T) { remoteURL: "https://gitlab.com/org/repo.git", want: "gitlab", }, + { + name: "forgejo codeberg", + remoteURL: "https://codeberg.org/org/repo.git", + want: "forgejo", + }, + { + name: "forgejo self-hosted hostname", + remoteURL: "https://forgejo.example.com/org/repo.git", + want: "forgejo", + }, { name: "HTTPS GitLab without .git", remoteURL: "https://gitlab.com/org/repo", diff --git a/internal/forge/forgejo/README.md b/internal/forge/forgejo/README.md new file mode 100644 index 0000000000..53382e8a7f --- /dev/null +++ b/internal/forge/forgejo/README.md @@ -0,0 +1,37 @@ +# Forgejo / Gitea `forge.Client` + +Implementation of `forge.Client` for Forgejo (and Gitea-compatible) API v1. + +ForgeOps backlog: **FACTORY-FULLSEND-FORGEJO-CLIENT-001** (ADR-0020 deferred item). + +## Usage + +```go +c := forgejo.New(os.Getenv("FORGEJO_TOKEN"), forgejo.WithBaseURL("https://codeberg.org")) +``` + +CLI wiring (`internal/cli/forge_client.go`) resolves: + +| Env | Role | +|---|---| +| `FORGEJO_TOKEN` / `GITEA_TOKEN` | Access token | +| `FORGEJO_API_URL` / `GITEA_API_URL` | Required API base (or manifest URL) | + +`forge.DetectForge` returns `"forgejo"` for `codeberg.org`, `gitea.com`, and hosts containing `forgejo`/`gitea`. Self-hosted hosts without those markers need `--forge forgejo`. + +## Coverage + +- Core REST methods (repos, issues, PRs, labels, branches, contents) are live. +- High-value: forks, multi-file commits (sequential/non-atomic), cross-repo PRs, issue comment CRUD, + PR reviews/commits/file diffs, branch protection reads, Actions secrets create/exists/delete, + `IsInstallationToken` → false, `GetTokenScopes` → nil (no OAuth scope enum). +- Actions workflows/runs/jobs/artifacts/variables, issue/comment reactions, PR authorization context, + and best-effort review threads (per review comment) are live via `actions_reactions.go`. +- Remaining methods (mostly GitLab CI / org-level Actions / annotations) return `forge.ErrNotSupported` via `stubs.go`. +- Live smoke: `go test ./internal/forge/forgejo/ -tags live_forgejo` with `FORGEJO_TOKEN` + `FORGEJO_API_URL` set. + +## Non-goals + +- Full repos.yaml install / converge parity for Forgejo +- GitLab pipeline APIs (stay stubs) +- GitHub GraphQL review-thread parity (Forgejo maps comments → threads) diff --git a/internal/forge/forgejo/actions_reactions.go b/internal/forge/forgejo/actions_reactions.go new file mode 100644 index 0000000000..b57476a28b --- /dev/null +++ b/internal/forge/forgejo/actions_reactions.go @@ -0,0 +1,653 @@ +package forgejo + +import ( + "context" + "encoding/json" + "fmt" + "hash/fnv" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" +) + +// validReactionContent mirrors GitHub/Gitea reaction content values. +var validReactionContent = map[string]struct{}{ + "+1": {}, "-1": {}, "laugh": {}, "confused": {}, "heart": {}, + "hooray": {}, "rocket": {}, "eyes": {}, +} + +func syntheticReactionID(content, user string) int64 { + h := fnv.New64a() + _, _ = h.Write([]byte(content)) + _, _ = h.Write([]byte{0}) + _, _ = h.Write([]byte(user)) + return int64(h.Sum64() & 0x7fffffffffffffff) +} + +type apiReaction struct { + Content string `json:"content"` + CreatedAt string `json:"created_at"` + User apiUser `json:"user"` +} + +func mapReaction(r apiReaction) forge.Reaction { + return forge.Reaction{ + ID: syntheticReactionID(r.Content, r.User.Login), + Content: r.Content, + User: r.User.Login, + } +} + +// AddIssueReaction implements forge.Client. +func (c *LiveClient) AddIssueReaction(ctx context.Context, owner, repo string, number int, content string) (int64, error) { + if _, ok := validReactionContent[content]; !ok { + return 0, fmt.Errorf("add issue reaction: invalid content %q", content) + } + var raw apiReaction + p := "/repos/" + escapePath(owner, repo) + "/issues/" + strconv.Itoa(number) + "/reactions" + if _, err := c.do(ctx, http.MethodPost, p, map[string]any{"content": content}, &raw); err != nil { + return 0, err + } + return mapReaction(raw).ID, nil +} + +// DeleteIssueReaction implements forge.Client. Forgejo deletes by content for +// the authenticated user; reactionID is matched via synthetic IDs from List. +func (c *LiveClient) DeleteIssueReaction(ctx context.Context, owner, repo string, number int, reactionID int64) error { + reactions, err := c.ListIssueReactions(ctx, owner, repo, number) + if err != nil { + return err + } + var content string + for _, r := range reactions { + if r.ID == reactionID { + content = r.Content + break + } + } + if content == "" { + return fmt.Errorf("delete issue reaction %d: %w", reactionID, forge.ErrNotFound) + } + p := "/repos/" + escapePath(owner, repo) + "/issues/" + strconv.Itoa(number) + "/reactions" + _, err = c.do(ctx, http.MethodDelete, p, map[string]any{"content": content}, nil) + return err +} + +// AddIssueCommentReaction implements forge.Client. +func (c *LiveClient) AddIssueCommentReaction(ctx context.Context, owner, repo string, commentID int, content string) (int64, error) { + if _, ok := validReactionContent[content]; !ok { + return 0, fmt.Errorf("add issue comment reaction: invalid content %q", content) + } + var raw apiReaction + p := "/repos/" + escapePath(owner, repo) + "/issues/comments/" + strconv.Itoa(commentID) + "/reactions" + if _, err := c.do(ctx, http.MethodPost, p, map[string]any{"content": content}, &raw); err != nil { + return 0, err + } + return mapReaction(raw).ID, nil +} + +// DeleteIssueCommentReaction implements forge.Client. +func (c *LiveClient) DeleteIssueCommentReaction(ctx context.Context, owner, repo string, commentID int, reactionID int64) error { + var raw []apiReaction + p := "/repos/" + escapePath(owner, repo) + "/issues/comments/" + strconv.Itoa(commentID) + "/reactions" + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return err + } + var content string + for _, r := range raw { + if mapReaction(r).ID == reactionID { + content = r.Content + break + } + } + if content == "" { + return fmt.Errorf("delete issue comment reaction %d: %w", reactionID, forge.ErrNotFound) + } + _, err := c.do(ctx, http.MethodDelete, p, map[string]any{"content": content}, nil) + return err +} + +// ListIssueReactions implements forge.Client. +func (c *LiveClient) ListIssueReactions(ctx context.Context, owner, repo string, number int) ([]forge.Reaction, error) { + var all []forge.Reaction + for page := 1; page <= 20; page++ { + var raw []apiReaction + p := fmt.Sprintf("/repos/%s/issues/%d/reactions?limit=50&page=%d", escapePath(owner, repo), number, page) + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + for _, r := range raw { + all = append(all, mapReaction(r)) + } + if len(raw) < 50 { + break + } + } + return all, nil +} + +// --- Actions variables / secret protection --------------------------------- + +// GetRepoSecretProtection implements forge.Client. +func (c *LiveClient) GetRepoSecretProtection(ctx context.Context, owner, repo, name string) (forge.SecretProtection, error) { + exists, err := c.RepoSecretExists(ctx, owner, repo, name) + if err != nil || !exists { + return forge.SecretProtection{}, err + } + return forge.SecretProtection{Exists: true, Masked: true, Protected: true}, nil +} + +// CreateOrUpdateRepoVariable implements forge.Client. +func (c *LiveClient) CreateOrUpdateRepoVariable(ctx context.Context, owner, repo, name, value string) error { + p := "/repos/" + escapePath(owner, repo) + "/actions/variables/" + url.PathEscape(name) + _, err := c.do(ctx, http.MethodPut, p, map[string]any{"value": value}, nil) + if err == nil { + return nil + } + if !forge.IsNotFound(err) { + // Try create when update fails for other reasons (e.g. 404-shaped messages). + _, err2 := c.do(ctx, http.MethodPost, p, map[string]any{"value": value}, nil) + if err2 == nil { + return nil + } + return fmt.Errorf("update variable %s: %v; create: %w", name, err, err2) + } + _, err = c.do(ctx, http.MethodPost, p, map[string]any{"value": value}, nil) + return err +} + +// RepoVariableExists implements forge.Client. +func (c *LiveClient) RepoVariableExists(ctx context.Context, owner, repo, name string) (bool, error) { + _, ok, err := c.GetRepoVariable(ctx, owner, repo, name) + return ok, err +} + +// GetRepoVariable implements forge.Client. +func (c *LiveClient) GetRepoVariable(ctx context.Context, owner, repo, name string) (string, bool, error) { + var raw struct { + Name string `json:"name"` + Data string `json:"data"` + } + p := "/repos/" + escapePath(owner, repo) + "/actions/variables/" + url.PathEscape(name) + code, err := c.do(ctx, http.MethodGet, p, nil, &raw) + if err != nil { + if code == http.StatusNotFound || forge.IsNotFound(err) { + return "", false, nil + } + return "", false, err + } + return raw.Data, true, nil +} + +// GetRepoVariableInfo implements forge.Client. +func (c *LiveClient) GetRepoVariableInfo(ctx context.Context, owner, repo, name string) (forge.RepoVariable, bool, error) { + value, exists, err := c.GetRepoVariable(ctx, owner, repo, name) + return forge.RepoVariable{Value: value}, exists, err +} + +// ListRepoVariables implements forge.Client. +func (c *LiveClient) ListRepoVariables(ctx context.Context, owner, repo string) (map[string]string, error) { + out := map[string]string{} + for page := 1; page <= 20; page++ { + var raw []struct { + Name string `json:"name"` + Data string `json:"data"` + } + p := fmt.Sprintf("/repos/%s/actions/variables?limit=50&page=%d", escapePath(owner, repo), page) + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + for _, v := range raw { + out[v.Name] = v.Data + } + if len(raw) < 50 { + break + } + } + return out, nil +} + +// DeleteRepoVariable implements forge.Client. +func (c *LiveClient) DeleteRepoVariable(ctx context.Context, owner, repo, name string) error { + p := "/repos/" + escapePath(owner, repo) + "/actions/variables/" + url.PathEscape(name) + _, err := c.do(ctx, http.MethodDelete, p, nil, nil) + return err +} + +// --- Actions workflows / runs ---------------------------------------------- + +type apiActionRun struct { + ID int64 `json:"id"` + Title string `json:"title"` + Event string `json:"event"` + TriggerEvt string `json:"trigger_event"` + Status string `json:"status"` + HTMLURL string `json:"html_url"` + Created string `json:"created"` + WorkflowID string `json:"workflow_id"` + PrettyRef string `json:"prettyref"` +} + +func mapActionRun(r apiActionRun) forge.WorkflowRun { + status, conclusion := mapActionRunStatus(r.Status) + event := r.Event + if event == "" { + event = r.TriggerEvt + } + return forge.WorkflowRun{ + ID: int(r.ID), + Name: r.Title, + Event: event, + Status: status, + Conclusion: conclusion, + HTMLURL: r.HTMLURL, + CreatedAt: r.Created, + Path: r.WorkflowID, + } +} + +func mapActionRunStatus(s string) (status, conclusion string) { + switch strings.ToLower(strings.TrimSpace(s)) { + case "success", "completed": + return "completed", "success" + case "failure", "failed": + return "completed", "failure" + case "cancelled", "canceled": + return "completed", "cancelled" + case "skipped": + return "completed", "skipped" + case "running", "in_progress": + return "in_progress", "" + case "waiting", "queued", "pending", "blocked": + return "queued", "" + default: + return s, "" + } +} + +func workflowFileMatches(workflowFile, workflowID, path string) bool { + if workflowFile == "" { + return true + } + wf := strings.TrimPrefix(workflowFile, "/") + for _, cand := range []string{workflowID, path} { + cand = strings.TrimPrefix(cand, "/") + if cand == "" { + continue + } + if cand == wf || strings.HasSuffix(cand, "/"+wf) || strings.HasSuffix(cand, wf) { + return true + } + if strings.EqualFold(cand, wf) { + return true + } + } + return false +} + +// GetWorkflow implements forge.Client best-effort via recent runs (no dedicated GET). +func (c *LiveClient) GetWorkflow(ctx context.Context, owner, repo, workflowFile string) (*forge.Workflow, error) { + runs, err := c.ListRecentWorkflowRuns(ctx, owner, repo, 50) + if err != nil { + return nil, err + } + for _, r := range runs { + if workflowFileMatches(workflowFile, r.Path, r.Name) { + return &forge.Workflow{ + ID: r.ID, + Name: r.Name, + Path: firstNonEmpty(r.Path, workflowFile), + State: "active", + }, nil + } + } + // Forgejo has no workflow catalog endpoint; treat unknown files as active + // so DispatchWorkflow can still be attempted by filename. + return &forge.Workflow{Name: workflowFile, Path: workflowFile, State: "active"}, nil +} + +func firstNonEmpty(vals ...string) string { + for _, v := range vals { + if v != "" { + return v + } + } + return "" +} + +// GetLatestWorkflowRun implements forge.Client. +func (c *LiveClient) GetLatestWorkflowRun(ctx context.Context, owner, repo, workflowFile string) (*forge.WorkflowRun, error) { + runs, err := c.ListWorkflowRuns(ctx, owner, repo, workflowFile) + if err != nil { + return nil, err + } + if len(runs) == 0 { + return nil, fmt.Errorf("no workflow runs found for %s", workflowFile) + } + return &runs[0], nil +} + +// GetWorkflowRun implements forge.Client. +func (c *LiveClient) GetWorkflowRun(ctx context.Context, owner, repo string, runID int) (*forge.WorkflowRun, error) { + var raw apiActionRun + p := "/repos/" + escapePath(owner, repo) + "/actions/runs/" + strconv.Itoa(runID) + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + m := mapActionRun(raw) + return &m, nil +} + +// DispatchWorkflow implements forge.Client. +func (c *LiveClient) DispatchWorkflow(ctx context.Context, owner, repo, workflowFile, ref string, inputs map[string]string) error { + payload := map[string]any{"ref": ref} + if len(inputs) > 0 { + payload["inputs"] = inputs + } + p := "/repos/" + escapePath(owner, repo) + "/actions/workflows/" + url.PathEscape(workflowFile) + "/dispatches" + _, err := c.do(ctx, http.MethodPost, p, payload, nil) + return err +} + +// ListWorkflowRuns implements forge.Client. +func (c *LiveClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflowFile string) ([]forge.WorkflowRun, error) { + runs, err := c.listActionRunsPage(ctx, owner, repo, 1, 30) + if err != nil { + return nil, err + } + out := make([]forge.WorkflowRun, 0, len(runs)) + for _, r := range runs { + m := mapActionRun(r) + if workflowFileMatches(workflowFile, r.WorkflowID, m.Path) { + out = append(out, m) + } + } + return out, nil +} + +// ListWorkflowRunsSince implements forge.Client. +func (c *LiveClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, workflowFile string, since time.Time) ([]forge.WorkflowRun, error) { + const maxPages = 50 + var all []forge.WorkflowRun + for page := 1; page <= maxPages; page++ { + runs, err := c.listActionRunsPage(ctx, owner, repo, page, 50) + if err != nil { + return nil, err + } + if len(runs) == 0 { + return all, nil + } + reachedBoundary := false + for _, r := range runs { + if !since.IsZero() { + if t, err := time.Parse(time.RFC3339, r.Created); err == nil && t.Before(since) { + reachedBoundary = true + break + } + } + if workflowFileMatches(workflowFile, r.WorkflowID, r.WorkflowID) { + all = append(all, mapActionRun(r)) + } + } + if reachedBoundary || len(runs) < 50 { + return all, nil + } + } + return nil, fmt.Errorf("list workflow runs since: pagination exceeded %d pages", maxPages) +} + +// ListRecentWorkflowRuns implements forge.Client. +func (c *LiveClient) ListRecentWorkflowRuns(ctx context.Context, owner, repo string, perPage int) ([]forge.WorkflowRun, error) { + if perPage <= 0 { + perPage = 30 + } + if perPage > 100 { + perPage = 100 + } + runs, err := c.listActionRunsPage(ctx, owner, repo, 1, perPage) + if err != nil { + return nil, err + } + out := make([]forge.WorkflowRun, 0, len(runs)) + for _, r := range runs { + out = append(out, mapActionRun(r)) + } + return out, nil +} + +func (c *LiveClient) listActionRunsPage(ctx context.Context, owner, repo string, page, limit int) ([]apiActionRun, error) { + p := fmt.Sprintf("/repos/%s/actions/runs?page=%d&limit=%d", escapePath(owner, repo), page, limit) + var raw json.RawMessage + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + var wrapped struct { + WorkflowRuns []apiActionRun `json:"workflow_runs"` + } + if len(raw) == 0 { + return nil, nil + } + if raw[0] == '{' { + if err := json.Unmarshal(raw, &wrapped); err != nil { + return nil, fmt.Errorf("decode action runs object: %w", err) + } + return wrapped.WorkflowRuns, nil + } + var bare []apiActionRun + if err := json.Unmarshal(raw, &bare); err != nil { + return nil, fmt.Errorf("decode action runs: %w", err) + } + return bare, nil +} + +// ListWorkflowRunJobs implements forge.Client. +func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string, runID int) ([]forge.WorkflowJob, error) { + var raw []struct { + ID int64 `json:"id"` + Name string `json:"name"` + Status string `json:"status"` + Attempt int `json:"attempt"` + } + p := "/repos/" + escapePath(owner, repo) + "/actions/runs/" + strconv.Itoa(runID) + "/jobs" + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.WorkflowJob, 0, len(raw)) + for _, j := range raw { + st, concl := mapActionRunStatus(j.Status) + out = append(out, forge.WorkflowJob{ + ID: int(j.ID), + RunAttempt: j.Attempt, + Name: j.Name, + Status: st, + Conclusion: concl, + }) + } + return out, nil +} + +// ListWorkflowRunArtifacts implements forge.Client. +func (c *LiveClient) ListWorkflowRunArtifacts(ctx context.Context, owner, repo string, runID int) ([]forge.WorkflowArtifact, error) { + var raw []struct { + ID int64 `json:"id"` + Name string `json:"name"` + } + p := "/repos/" + escapePath(owner, repo) + "/actions/runs/" + strconv.Itoa(runID) + "/artifacts" + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.WorkflowArtifact, 0, len(raw)) + for _, a := range raw { + out = append(out, forge.WorkflowArtifact{ID: int(a.ID), Name: a.Name}) + } + return out, nil +} + +// DownloadWorkflowRunArtifact implements forge.Client. +func (c *LiveClient) DownloadWorkflowRunArtifact(ctx context.Context, owner, repo string, artifactID int) ([]byte, error) { + // Prefer zip endpoint; fall back to artifact metadata URL is not needed. + p := "/repos/" + escapePath(owner, repo) + "/actions/artifacts/" + strconv.Itoa(artifactID) + "/zip" + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+p, nil) + if err != nil { + return nil, err + } + if c.token != "" { + req.Header.Set("Authorization", "token "+c.token) + } + res, err := c.http.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode == http.StatusNotFound { + return nil, forge.ErrNotFound + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + return nil, fmt.Errorf("download artifact %d: HTTP %d", artifactID, res.StatusCode) + } + return io.ReadAll(res.Body) +} + +// ListRepositoryArtifacts implements forge.Client. +func (c *LiveClient) ListRepositoryArtifacts(ctx context.Context, owner, repo string, perPage int) ([]forge.RepositoryArtifact, error) { + if perPage <= 0 { + perPage = 30 + } + var raw []struct { + ID int64 `json:"id"` + Name string `json:"name"` + CreatedAt string `json:"created_at"` + RunID int64 `json:"run_id"` + } + p := fmt.Sprintf("/repos/%s/actions/artifacts?limit=%d", escapePath(owner, repo), perPage) + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.RepositoryArtifact, 0, len(raw)) + for _, a := range raw { + out = append(out, forge.RepositoryArtifact{ + ID: int(a.ID), + Name: a.Name, + CreatedAt: a.CreatedAt, + WorkflowRunID: int(a.RunID), + }) + } + return out, nil +} + +// GetWorkflowRunLogs implements forge.Client. +func (c *LiveClient) GetWorkflowRunLogs(ctx context.Context, owner, repo string, runID int) (string, error) { + p := "/repos/" + escapePath(owner, repo) + "/actions/runs/" + strconv.Itoa(runID) + "/logs" + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+p, nil) + if err != nil { + return "", err + } + if c.token != "" { + req.Header.Set("Authorization", "token "+c.token) + } + res, err := c.http.Do(req) + if err != nil { + return "", err + } + defer res.Body.Close() + if res.StatusCode == http.StatusNotFound { + return "", forge.ErrNotFound + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + return "", fmt.Errorf("get workflow run logs %d: HTTP %d", runID, res.StatusCode) + } + b, err := io.ReadAll(res.Body) + if err != nil { + return "", err + } + return string(b), nil +} + +// --- PR authorization + review threads ------------------------------------- + +// GetPullRequestAuthorizationContext implements forge.Client. +func (c *LiveClient) GetPullRequestAuthorizationContext(ctx context.Context, owner, repo string, number int) (*forge.PullRequestAuthorizationContext, error) { + var pr struct { + UpdatedAt string `json:"updated_at"` + User apiUser `json:"user"` + Labels []struct { + Name string `json:"name"` + } `json:"labels"` + } + p := "/repos/" + escapePath(owner, repo) + "/pulls/" + strconv.Itoa(number) + if _, err := c.do(ctx, http.MethodGet, p, nil, &pr); err != nil { + return nil, err + } + labels := make([]string, 0, len(pr.Labels)) + for _, l := range pr.Labels { + labels = append(labels, l.Name) + } + return &forge.PullRequestAuthorizationContext{ + AuthorLogin: pr.User.Login, + UpdatedAt: pr.UpdatedAt, + Labels: labels, + }, nil +} + +// ListPullRequestReviewThreads maps Forgejo review comments to ReviewThread +// entries (one thread per comment; no GraphQL thread grouping). +func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, repo string, number int) (forge.ReviewThreadPage, error) { + reviews, err := c.ListPullRequestReviews(ctx, owner, repo, number) + if err != nil { + return forge.ReviewThreadPage{}, err + } + page := forge.ReviewThreadPage{} + const capThreads = 500 + for _, rev := range reviews { + var comments []struct { + ID int `json:"id"` + Body string `json:"body"` + Path string `json:"path"` + Position int `json:"position"` + CreatedAt string `json:"created_at"` + User apiUser `json:"user"` + Resolver *apiUser `json:"resolver"` + } + p := "/repos/" + escapePath(owner, repo) + "/pulls/" + strconv.Itoa(number) + "/reviews/" + strconv.Itoa(rev.ID) + "/comments" + if _, err := c.do(ctx, http.MethodGet, p, nil, &comments); err != nil { + return forge.ReviewThreadPage{}, err + } + for _, cm := range comments { + if len(page.Threads) >= capThreads { + page.Truncated = true + return page, nil + } + side := forge.DiffSideRight + line := cm.Position + thread := forge.ReviewThread{ + ID: strconv.Itoa(cm.ID), + IsResolved: cm.Resolver != nil && cm.Resolver.Login != "", + Path: cm.Path, + Side: &side, + ResolvedByRole: normevent.RoleNone, + Comments: []forge.ReviewThreadComment{{ + Author: cm.User.Login, + AuthorType: "User", + Body: cm.Body, + CreatedAt: cm.CreatedAt, + }}, + } + if line > 0 { + thread.Line = &line + thread.NewLine = &line + } + if cm.Resolver != nil { + thread.ResolvedBy = cm.Resolver.Login + thread.ResolvedByType = "User" + } + page.Threads = append(page.Threads, thread) + } + } + return page, nil +} diff --git a/internal/forge/forgejo/actions_reactions_test.go b/internal/forge/forgejo/actions_reactions_test.go new file mode 100644 index 0000000000..2ae4104523 --- /dev/null +++ b/internal/forge/forgejo/actions_reactions_test.go @@ -0,0 +1,144 @@ +package forgejo + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +func TestReactionsAndWorkflowRuns(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/repos/o/r/issues/1/reactions", func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPost: + _ = json.NewEncoder(w).Encode(map[string]any{ + "content": "+1", "user": map[string]any{"login": "alice"}, + }) + case http.MethodGet: + _ = json.NewEncoder(w).Encode([]map[string]any{{ + "content": "+1", "user": map[string]any{"login": "alice"}, + }}) + case http.MethodDelete: + w.WriteHeader(http.StatusOK) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) + mux.HandleFunc("/api/v1/repos/o/r/actions/runs", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "total_count": 1, + "workflow_runs": []map[string]any{{ + "id": 7, "title": "CI", "event": "push", "status": "success", + "html_url": "https://example/run/7", "created": time.Now().UTC().Format(time.RFC3339), + "workflow_id": "ci.yaml", + }}, + }) + }) + mux.HandleFunc("/api/v1/repos/o/r/actions/workflows/ci.yaml/dispatches", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("/api/v1/repos/o/r/pulls/3", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "updated_at": "2026-01-02T03:04:05Z", + "user": map[string]any{"login": "bob"}, + "labels": []map[string]any{{"name": "ok"}}, + }) + }) + mux.HandleFunc("/api/v1/repos/o/r/pulls/3/reviews", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode([]map[string]any{{ + "id": 9, "body": "LGTM", "state": "APPROVED", + "user": map[string]any{"login": "rev"}, "submitted_at": "2026-01-02T03:04:05Z", + }}) + }) + mux.HandleFunc("/api/v1/repos/o/r/pulls/3/reviews/9/comments", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode([]map[string]any{{ + "id": 11, "body": "nit", "path": "a.go", "position": 4, + "created_at": "2026-01-02T03:04:05Z", + "user": map[string]any{"login": "rev"}, + }}) + }) + mux.HandleFunc("/api/v1/repos/o/r/actions/variables/FOO", func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"name": "FOO", "data": "bar"}) + case http.MethodPut, http.MethodPost: + w.WriteHeader(http.StatusNoContent) + case http.MethodDelete: + w.WriteHeader(http.StatusNoContent) + } + }) + mux.HandleFunc("/api/v1/repos/o/r/actions/variables", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode([]map[string]any{{"name": "FOO", "data": "bar"}}) + }) + + srv := httptest.NewServer(mux) + defer srv.Close() + c := New("tok", WithBaseURL(srv.URL)) + + id, err := c.AddIssueReaction(context.Background(), "o", "r", 1, "+1") + if err != nil { + t.Fatal(err) + } + if id == 0 { + t.Fatal("expected synthetic reaction id") + } + rs, err := c.ListIssueReactions(context.Background(), "o", "r", 1) + if err != nil || len(rs) != 1 || rs[0].Content != "+1" { + t.Fatalf("reactions=%v err=%v", rs, err) + } + if err := c.DeleteIssueReaction(context.Background(), "o", "r", 1, id); err != nil { + t.Fatal(err) + } + + runs, err := c.ListWorkflowRuns(context.Background(), "o", "r", "ci.yaml") + if err != nil || len(runs) != 1 || runs[0].Conclusion != "success" { + t.Fatalf("runs=%v err=%v", runs, err) + } + if err := c.DispatchWorkflow(context.Background(), "o", "r", "ci.yaml", "main", nil); err != nil { + t.Fatal(err) + } + + auth, err := c.GetPullRequestAuthorizationContext(context.Background(), "o", "r", 3) + if err != nil || auth.AuthorLogin != "bob" || len(auth.Labels) != 1 { + t.Fatalf("auth=%+v err=%v", auth, err) + } + page, err := c.ListPullRequestReviewThreads(context.Background(), "o", "r", 3) + if err != nil || len(page.Threads) != 1 || page.Threads[0].Path != "a.go" { + t.Fatalf("threads=%+v err=%v", page, err) + } + + if err := c.CreateOrUpdateRepoVariable(context.Background(), "o", "r", "FOO", "bar"); err != nil { + t.Fatal(err) + } + val, ok, err := c.GetRepoVariable(context.Background(), "o", "r", "FOO") + if err != nil || !ok || val != "bar" { + t.Fatalf("var=%q ok=%v err=%v", val, ok, err) + } + vars, err := c.ListRepoVariables(context.Background(), "o", "r") + if err != nil || vars["FOO"] != "bar" { + t.Fatalf("vars=%v err=%v", vars, err) + } +} + +func TestGetTokenScopesNil(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/user", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"login": "u"}) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + c := New("tok", WithBaseURL(srv.URL)) + scopes, err := c.GetTokenScopes(context.Background()) + if err != nil { + t.Fatal(err) + } + if scopes != nil { + t.Fatalf("want nil scopes, got %v", scopes) + } + _ = forge.ErrNotSupported // keep import used if trimmed later +} diff --git a/internal/forge/forgejo/client.go b/internal/forge/forgejo/client.go new file mode 100644 index 0000000000..d6f12025e5 --- /dev/null +++ b/internal/forge/forgejo/client.go @@ -0,0 +1,231 @@ +// Package forgejo implements forge.Client for the Forgejo / Gitea API v1. +// +// ForgeOps FACTORY-FULLSEND-FORGEJO-CLIENT-001: Forgejo/Gitea forge.Client. +// Callers must configure WithBaseURL. Remaining GitLab-only / unsupported +// methods return forge.ErrNotSupported (see stubs.go). +package forgejo + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +// Compile-time interface check. +var _ forge.Client = (*LiveClient)(nil) + +// LiveClient talks to a Forgejo (or Gitea-compatible) instance. +type LiveClient struct { + http *http.Client + token string + baseURL string // e.g. https://codeberg.org/api/v1 +} + +// Option configures LiveClient. +type Option func(*LiveClient) + +// WithBaseURL sets the API root (must include /api/v1 or will be appended). +func WithBaseURL(raw string) Option { + return func(c *LiveClient) { + c.baseURL = normalizeAPIBase(raw) + } +} + +func normalizeAPIBase(raw string) string { + raw = strings.TrimRight(raw, "/") + if strings.HasSuffix(raw, "/api/v1") { + return raw + } + return raw + "/api/v1" +} + +// New returns a Forgejo client. Callers must set a base URL with WithBaseURL +// (or CLI FORGEJO_API_URL / GITEA_API_URL). There is no hardcoded default host. +func New(token string, opts ...Option) *LiveClient { + c := &LiveClient{ + http: &http.Client{Timeout: 60 * time.Second}, + token: token, + } + for _, opt := range opts { + opt(c) + } + return c +} + +// BaseURL returns the configured API base. +func (c *LiveClient) BaseURL() string { return c.baseURL } + +func (c *LiveClient) do(ctx context.Context, method, path string, in any, out any) (int, error) { + if c.baseURL == "" { + return 0, fmt.Errorf("forgejo client: base URL not configured (use WithBaseURL or FORGEJO_API_URL)") + } + var body io.Reader + if in != nil { + b, err := json.Marshal(in) + if err != nil { + return 0, err + } + body = bytes.NewReader(b) + } + u := c.baseURL + path + req, err := http.NewRequestWithContext(ctx, method, u, body) + if err != nil { + return 0, err + } + if c.token != "" { + req.Header.Set("Authorization", "token "+c.token) + } + if in != nil { + req.Header.Set("Content-Type", "application/json") + } + req.Header.Set("Accept", "application/json") + res, err := c.http.Do(req) + if err != nil { + return 0, err + } + defer res.Body.Close() + data, err := io.ReadAll(res.Body) + if err != nil { + return res.StatusCode, err + } + if res.StatusCode == http.StatusNotFound { + return res.StatusCode, fmt.Errorf("%s %s: %w", method, path, forge.ErrNotFound) + } + if res.StatusCode == http.StatusConflict { + return res.StatusCode, fmt.Errorf("%s %s: %w", method, path, forge.ErrConflict) + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + return res.StatusCode, fmt.Errorf("%s %s: HTTP %d: %s", method, path, res.StatusCode, truncate(string(data), 300)) + } + if out != nil && len(data) > 0 && res.StatusCode != http.StatusNoContent { + if err := json.Unmarshal(data, out); err != nil { + return res.StatusCode, fmt.Errorf("decode %s: %w", path, err) + } + } + return res.StatusCode, nil +} + +func truncate(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] + "…" +} + +func escapePath(parts ...string) string { + enc := make([]string, len(parts)) + for i, p := range parts { + enc[i] = url.PathEscape(p) + } + return strings.Join(enc, "/") +} + +type apiUser struct { + ID int64 `json:"id"` + Login string `json:"login"` + FullName string `json:"full_name"` + Email string `json:"email"` +} + +type apiRepo struct { + ID int64 `json:"id"` + Name string `json:"name"` + FullName string `json:"full_name"` + Description string `json:"description"` + Private bool `json:"private"` + Fork bool `json:"fork"` + Archived bool `json:"archived"` + DefaultBranch string `json:"default_branch"` + Owner struct { + Login string `json:"login"` + } `json:"owner"` + CloneURL string `json:"clone_url"` + HTMLURL string `json:"html_url"` +} + +// GetAuthenticatedUser implements forge.Client. +func (c *LiveClient) GetAuthenticatedUser(ctx context.Context) (string, error) { + var u apiUser + if _, err := c.do(ctx, http.MethodGet, "/user", nil, &u); err != nil { + return "", err + } + return u.Login, nil +} + +// GetTokenScopes implements forge.Client. Forgejo does not expose OAuth scope +// enumeration; return nil so preflight skips scope checks (same as unknown-scope path). +func (c *LiveClient) GetTokenScopes(ctx context.Context) ([]string, error) { + if _, err := c.GetAuthenticatedUser(ctx); err != nil { + return nil, err + } + return nil, nil +} + +// ListOrgRepos implements forge.Client. +func (c *LiveClient) ListOrgRepos(ctx context.Context, org string, includePrivate bool) ([]forge.Repository, error) { + var raw []apiRepo + path := "/orgs/" + url.PathEscape(org) + "/repos?limit=100" + if _, err := c.do(ctx, http.MethodGet, path, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.Repository, 0, len(raw)) + for _, r := range raw { + if r.Archived || r.Fork { + continue + } + if !includePrivate && r.Private { + continue + } + out = append(out, mapRepo(r)) + } + return out, nil +} + +// GetRepo implements forge.Client. +func (c *LiveClient) GetRepo(ctx context.Context, owner, repo string) (*forge.Repository, error) { + var r apiRepo + path := "/repos/" + escapePath(owner, repo) + if _, err := c.do(ctx, http.MethodGet, path, nil, &r); err != nil { + return nil, err + } + m := mapRepo(r) + return &m, nil +} + +// CreateRepo implements forge.Client. +func (c *LiveClient) CreateRepo(ctx context.Context, org, name, description string, private bool) (*forge.Repository, error) { + payload := map[string]any{ + "name": name, + "description": description, + "private": private, + "auto_init": true, + } + var r apiRepo + path := "/orgs/" + url.PathEscape(org) + "/repos" + if _, err := c.do(ctx, http.MethodPost, path, payload, &r); err != nil { + return nil, err + } + m := mapRepo(r) + return &m, nil +} + +// UpdateRepoVisibility implements forge.Client. +func (c *LiveClient) UpdateRepoVisibility(ctx context.Context, owner, repo string, private bool) error { + payload := map[string]any{"private": private} + _, err := c.do(ctx, http.MethodPatch, "/repos/"+escapePath(owner, repo), payload, nil) + return err +} + +// DeleteRepo implements forge.Client. +func (c *LiveClient) DeleteRepo(ctx context.Context, owner, repo string) error { + _, err := c.do(ctx, http.MethodDelete, "/repos/"+escapePath(owner, repo), nil, nil) + return err +} diff --git a/internal/forge/forgejo/client_test.go b/internal/forge/forgejo/client_test.go new file mode 100644 index 0000000000..0bb22a5c39 --- /dev/null +++ b/internal/forge/forgejo/client_test.go @@ -0,0 +1,55 @@ +package forgejo + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +func TestDetectCompileTimeInterface(t *testing.T) { + var _ forge.Client = New("tok") +} + +func TestGetRepoAndUser(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/user", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "login": "mrgeek", "full_name": "Mr Geek", "email": "a@b.c"}) + }) + mux.HandleFunc("/api/v1/repos/forgeops-ai/forge-platform", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 9, "name": "forge-platform", "full_name": "forgeops-ai/forge-platform", + "private": true, "default_branch": "main", + "owner": map[string]any{"login": "forgeops-ai"}, + }) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + c := New("test-token", WithBaseURL(srv.URL+"/api/v1")) + login, err := c.GetAuthenticatedUser(context.Background()) + if err != nil { + t.Fatal(err) + } + if login != "mrgeek" { + t.Fatalf("login=%q", login) + } + repo, err := c.GetRepo(context.Background(), "forgeops-ai", "forge-platform") + if err != nil { + t.Fatal(err) + } + if repo.Name != "forge-platform" || !repo.Private { + t.Fatalf("repo=%+v", repo) + } +} + +func TestUnsupportedStub(t *testing.T) { + c := New("x", WithBaseURL("http://127.0.0.1:9/api/v1")) + _, err := c.CreatePipeline(context.Background(), "o", "r", "main", nil) + if !forge.IsNotSupported(err) { + t.Fatalf("want ErrNotSupported, got %v", err) + } +} diff --git a/internal/forge/forgejo/highvalue.go b/internal/forge/forgejo/highvalue.go new file mode 100644 index 0000000000..a1f17062d0 --- /dev/null +++ b/internal/forge/forgejo/highvalue.go @@ -0,0 +1,457 @@ +package forgejo + +import ( + "context" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +// --- forks ----------------------------------------------------------------- + +// FindExistingFork implements forge.Client. +func (c *LiveClient) FindExistingFork(ctx context.Context, owner, repo string) (string, string, error) { + user, err := c.GetAuthenticatedUser(ctx) + if err != nil { + return "", "", err + } + var r apiRepo + code, err := c.do(ctx, http.MethodGet, "/repos/"+escapePath(user, repo), nil, &r) + if err != nil { + if code == http.StatusNotFound || forge.IsNotFound(err) { + return "", "", nil + } + return "", "", err + } + if r.Fork { + // Parent may be present on Forgejo fork payloads. + parent := "" + var full struct { + Fork bool `json:"fork"` + Parent *struct { + FullName string `json:"full_name"` + } `json:"parent"` + Name string `json:"name"` + Owner struct { + Login string `json:"login"` + } `json:"owner"` + } + if _, err := c.do(ctx, http.MethodGet, "/repos/"+escapePath(user, repo), nil, &full); err == nil { + if full.Parent != nil { + parent = full.Parent.FullName + } + if full.Fork && parent == owner+"/"+repo { + return full.Owner.Login, full.Name, nil + } + } + } + return "", "", nil +} + +// CreateFork implements forge.Client. +func (c *LiveClient) CreateFork(ctx context.Context, owner, repo string) (string, string, error) { + var fork apiRepo + if _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/forks", map[string]any{}, &fork); err != nil { + return "", "", err + } + return fork.Owner.Login, fork.Name, nil +} + +// CreateForkInOrg implements forge.Client. +func (c *LiveClient) CreateForkInOrg(ctx context.Context, owner, repo, org, forkName string) (string, error) { + source := owner + "/" + repo + var existing apiRepo + code, err := c.do(ctx, http.MethodGet, "/repos/"+escapePath(org, forkName), nil, &existing) + if err == nil && code == http.StatusOK { + var full struct { + Fork bool `json:"fork"` + Name string `json:"name"` + Parent *struct { + FullName string `json:"full_name"` + } `json:"parent"` + } + if _, e2 := c.do(ctx, http.MethodGet, "/repos/"+escapePath(org, forkName), nil, &full); e2 == nil { + if !full.Fork { + return "", fmt.Errorf("repo %s/%s already exists and is not a fork: %w", org, forkName, forge.ErrNotFork) + } + if full.Parent != nil && full.Parent.FullName != source { + return "", fmt.Errorf("repo %s/%s is a fork of %s, not %s: %w", org, forkName, full.Parent.FullName, source, forge.ErrNotFork) + } + return full.Name, nil + } + } + payload := map[string]any{"organization": org} + if forkName != "" { + payload["name"] = forkName + } + var fork apiRepo + if _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/forks", payload, &fork); err != nil { + return "", err + } + return fork.Name, nil +} + +// --- file commits ---------------------------------------------------------- + +// UpdateFileIfMatch implements forge.Client. +func (c *LiveClient) UpdateFileIfMatch(ctx context.Context, owner, repo, path, message string, content []byte, expectedSHA string) error { + ct, err := c.getContents(ctx, owner, repo, path, "") + if err != nil { + return err + } + if ct.SHA != expectedSHA { + return fmt.Errorf("update %s: sha mismatch want %s got %s: %w", path, expectedSHA, ct.SHA, forge.ErrConflict) + } + return c.putFile(ctx, owner, repo, path, message, "", content, expectedSHA) +} + +// DeleteFiles implements forge.Client. +func (c *LiveClient) DeleteFiles(ctx context.Context, owner, repo, message string, paths []string) (int, error) { + n := 0 + for _, p := range paths { + if err := c.DeleteFile(ctx, owner, repo, p, message); err != nil { + if forge.IsNotFound(err) { + continue + } + return n, err + } + n++ + } + return n, nil +} + +// CommitFiles implements forge.Client via sequential contents API (not atomic tree). +func (c *LiveClient) CommitFiles(ctx context.Context, owner, repo, message string, files []forge.TreeFile) (bool, error) { + r, err := c.GetRepo(ctx, owner, repo) + if err != nil { + return false, err + } + return c.CommitFilesToBranch(ctx, owner, repo, r.DefaultBranch, message, files) +} + +// CommitFilesToBranch implements forge.Client via sequential contents API. +// Not atomic: a mid-batch failure may leave earlier file writes committed. +func (c *LiveClient) CommitFilesToBranch(ctx context.Context, owner, repo, branch, message string, files []forge.TreeFile) (bool, error) { + if len(files) == 0 { + return false, nil + } + changed := false + for _, f := range files { + if f.Delete { + ct, err := c.getContents(ctx, owner, repo, f.Path, branch) + if err != nil { + if forge.IsNotFound(err) { + continue + } + return changed, err + } + payload := map[string]any{"message": message, "sha": ct.SHA, "branch": branch} + p := "/repos/" + escapePath(owner, repo) + "/contents/" + strings.TrimPrefix(f.Path, "/") + if _, err := c.do(ctx, http.MethodDelete, p, payload, nil); err != nil { + return changed, err + } + changed = true + continue + } + content, err := f.Bytes() + if err != nil { + return changed, err + } + if err := c.CreateOrUpdateFileOnBranch(ctx, owner, repo, branch, f.Path, message, content); err != nil { + return changed, err + } + changed = true + } + return changed, nil +} + +// ForceCommitFileToBranch implements forge.Client. +func (c *LiveClient) ForceCommitFileToBranch(ctx context.Context, owner, repo, branch, path, message string, content []byte) error { + return c.CreateOrUpdateFileOnBranch(ctx, owner, repo, branch, path, message, content) +} + +// CreateCrossRepoChangeProposal implements forge.Client. +func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwner, baseRepo, headOwner, headRepo, title, body, headBranch, baseBranch string) (*forge.ChangeProposal, error) { + _ = headRepo // Forgejo head uses owner:branch; head repo name must match fork naming. + head := headOwner + ":" + headBranch + return c.CreateChangeProposal(ctx, baseOwner, baseRepo, title, body, head, baseBranch) +} + +// IsInstallationToken implements forge.Client — Forgejo personal tokens are not GH App installs. +func (c *LiveClient) IsInstallationToken(ctx context.Context) (bool, error) { + if _, err := c.GetAuthenticatedUser(ctx); err != nil { + return false, err + } + return false, nil +} + +// --- comments / labels ----------------------------------------------------- + +// GetIssueComment implements forge.Client. +func (c *LiveClient) GetIssueComment(ctx context.Context, owner, repo string, commentID int) (*forge.IssueComment, error) { + var raw struct { + ID int `json:"id"` + Body string `json:"body"` + User struct { + Login string `json:"login"` + } `json:"user"` + Created string `json:"created_at"` + } + p := "/repos/" + escapePath(owner, repo) + "/issues/comments/" + fmt.Sprintf("%d", commentID) + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + return &forge.IssueComment{ID: raw.ID, Body: raw.Body, Author: raw.User.Login, CreatedAt: raw.Created}, nil +} + +// UpdateIssueComment implements forge.Client. +func (c *LiveClient) UpdateIssueComment(ctx context.Context, owner, repo string, commentID int, body string) error { + p := "/repos/" + escapePath(owner, repo) + "/issues/comments/" + fmt.Sprintf("%d", commentID) + _, err := c.do(ctx, http.MethodPatch, p, map[string]any{"body": body}, nil) + return err +} + +// DeleteIssueComment implements forge.Client. +func (c *LiveClient) DeleteIssueComment(ctx context.Context, owner, repo string, commentID int) error { + p := "/repos/" + escapePath(owner, repo) + "/issues/comments/" + fmt.Sprintf("%d", commentID) + _, err := c.do(ctx, http.MethodDelete, p, nil, nil) + return err +} + +// RemoveIssueLabel implements forge.Client. +func (c *LiveClient) RemoveIssueLabel(ctx context.Context, owner, repo string, number int, label string) error { + p := "/repos/" + escapePath(owner, repo) + "/issues/" + fmt.Sprintf("%d", number) + "/labels/" + url.PathEscape(label) + _, err := c.do(ctx, http.MethodDelete, p, nil, nil) + return err +} + +// --- pull request review --------------------------------------------------- + +// ListPullRequestCommits implements forge.Client. +func (c *LiveClient) ListPullRequestCommits(ctx context.Context, owner, repo string, number int) ([]string, error) { + var raw []struct { + SHA string `json:"sha"` + } + p := "/repos/" + escapePath(owner, repo) + "/pulls/" + fmt.Sprintf("%d", number) + "/commits?limit=100" + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]string, 0, len(raw)) + for _, cmt := range raw { + out = append(out, cmt.SHA) + } + return out, nil +} + +// ListPullRequestFileDiffs implements forge.Client. +func (c *LiveClient) ListPullRequestFileDiffs(ctx context.Context, owner, repo string, number int) ([]forge.PullRequestFileDiff, error) { + var raw []struct { + Filename string `json:"filename"` + Status string `json:"status"` + Patch string `json:"patch"` + Previous string `json:"previous_filename"` + } + p := "/repos/" + escapePath(owner, repo) + "/pulls/" + fmt.Sprintf("%d", number) + "/files?limit=100" + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.PullRequestFileDiff, 0, len(raw)) + for _, f := range raw { + st := f.Status + switch st { + case "added", "removed", "renamed", "modified", "copied": + default: + st = "modified" + } + out = append(out, forge.PullRequestFileDiff{ + Path: f.Filename, + PreviousPath: f.Previous, + Status: st, + Patch: f.Patch, + }) + } + return out, nil +} + +// CreatePullRequestReview implements forge.Client. +func (c *LiveClient) CreatePullRequestReview(ctx context.Context, owner, repo string, number int, event, body, commitSHA string, comments []forge.ReviewComment) error { + switch event { + case "APPROVE", "REQUEST_CHANGES", "COMMENT": + default: + return fmt.Errorf("create review on #%d: invalid event %q", number, event) + } + payload := map[string]any{ + "event": event, + "body": body, + } + if commitSHA != "" { + payload["commit_id"] = commitSHA + } + if len(comments) > 0 { + cms := make([]map[string]any, 0, len(comments)) + for _, rc := range comments { + cm := map[string]any{"path": rc.Path, "body": rc.Body} + if rc.Line > 0 { + cm["new_position"] = rc.Line + } + cms = append(cms, cm) + } + payload["comments"] = cms + } + p := "/repos/" + escapePath(owner, repo) + "/pulls/" + fmt.Sprintf("%d", number) + "/reviews" + _, err := c.do(ctx, http.MethodPost, p, payload, nil) + return err +} + +// ListPullRequestReviews implements forge.Client. +func (c *LiveClient) ListPullRequestReviews(ctx context.Context, owner, repo string, number int) ([]forge.PullRequestReview, error) { + var raw []struct { + ID int `json:"id"` + Body string `json:"body"` + State string `json:"state"` + User struct { + Login string `json:"login"` + } `json:"user"` + SubmittedAt string `json:"submitted_at"` + } + p := "/repos/" + escapePath(owner, repo) + "/pulls/" + fmt.Sprintf("%d", number) + "/reviews" + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.PullRequestReview, 0, len(raw)) + for _, r := range raw { + out = append(out, forge.PullRequestReview{ + ID: r.ID, + User: r.User.Login, + State: r.State, + Body: r.Body, + SubmittedAt: r.SubmittedAt, + }) + } + return out, nil +} + +// DismissPullRequestReview implements forge.Client. +func (c *LiveClient) DismissPullRequestReview(ctx context.Context, owner, repo string, number, reviewID int, message string) error { + p := "/repos/" + escapePath(owner, repo) + "/pulls/" + fmt.Sprintf("%d", number) + "/reviews/" + fmt.Sprintf("%d", reviewID) + "/dismissals" + _, err := c.do(ctx, http.MethodPost, p, map[string]any{"message": message}, nil) + return err +} + +// UpdatePullRequestBranch implements forge.Client. +func (c *LiveClient) UpdatePullRequestBranch(ctx context.Context, owner, repo string, number int) error { + p := "/repos/" + escapePath(owner, repo) + "/pulls/" + fmt.Sprintf("%d", number) + "/update" + _, err := c.do(ctx, http.MethodPost, p, nil, nil) + return err +} + +// --- branch protection ----------------------------------------------------- + +// IsProtectedBranch implements forge.Client. +func (c *LiveClient) IsProtectedBranch(ctx context.Context, owner, repo, branch string) (bool, error) { + rule, err := c.GetProtectedBranch(ctx, owner, repo, branch) + if err != nil { + return false, err + } + return rule != nil, nil +} + +// GetProtectedBranch implements forge.Client. +func (c *LiveClient) GetProtectedBranch(ctx context.Context, owner, repo, branch string) (*forge.ProtectedBranchRule, error) { + var raw struct { + EnablePush bool `json:"enable_push"` + EnableMergeWhitelist bool `json:"enable_merge_whitelist"` + BranchName string `json:"branch_name"` + Protected bool `json:"protected"` + } + p := "/repos/" + escapePath(owner, repo) + "/branch_protections/" + url.PathEscape(branch) + code, err := c.do(ctx, http.MethodGet, p, nil, &raw) + if err == nil { + name := raw.BranchName + if name == "" { + name = branch + } + return &forge.ProtectedBranchRule{Name: name}, nil + } + if code != http.StatusNotFound && !forge.IsNotFound(err) { + return nil, err + } + // Fall back to branch endpoint (includes effective protection). + var br struct { + Name string `json:"name"` + Protected bool `json:"protected"` + } + bp := "/repos/" + escapePath(owner, repo) + "/branches/" + url.PathEscape(branch) + code2, err2 := c.do(ctx, http.MethodGet, bp, nil, &br) + if err2 != nil { + if code2 == http.StatusNotFound || forge.IsNotFound(err2) { + return nil, nil + } + return nil, err2 + } + if !br.Protected { + return nil, nil + } + name := br.Name + if name == "" { + name = branch + } + return &forge.ProtectedBranchRule{Name: name}, nil +} + +// ListProtectedBranches implements forge.Client. +func (c *LiveClient) ListProtectedBranches(ctx context.Context, owner, repo string) ([]forge.ProtectedBranchRule, error) { + var raw []struct { + BranchName string `json:"branch_name"` + RuleName string `json:"rule_name"` + } + p := "/repos/" + escapePath(owner, repo) + "/branch_protections" + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.ProtectedBranchRule, 0, len(raw)) + for _, r := range raw { + name := r.BranchName + if name == "" { + name = r.RuleName + } + out = append(out, forge.ProtectedBranchRule{Name: name}) + } + return out, nil +} + +// --- actions secrets (best-effort Forgejo/Gitea API) ----------------------- + +// CreateRepoSecret implements forge.Client. +func (c *LiveClient) CreateRepoSecret(ctx context.Context, owner, repo, name, value string) error { + p := "/repos/" + escapePath(owner, repo) + "/actions/secrets/" + url.PathEscape(name) + _, err := c.do(ctx, http.MethodPut, p, map[string]any{"data": value}, nil) + return err +} + +// RepoSecretExists implements forge.Client. +func (c *LiveClient) RepoSecretExists(ctx context.Context, owner, repo, name string) (bool, error) { + var raw []struct { + Name string `json:"name"` + } + p := "/repos/" + escapePath(owner, repo) + "/actions/secrets" + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return false, err + } + for _, s := range raw { + if s.Name == name { + return true, nil + } + } + return false, nil +} + +// DeleteRepoSecret implements forge.Client. +func (c *LiveClient) DeleteRepoSecret(ctx context.Context, owner, repo, name string) error { + p := "/repos/" + escapePath(owner, repo) + "/actions/secrets/" + url.PathEscape(name) + _, err := c.do(ctx, http.MethodDelete, p, nil, nil) + return err +} diff --git a/internal/forge/forgejo/highvalue_test.go b/internal/forge/forgejo/highvalue_test.go new file mode 100644 index 0000000000..b132943aa1 --- /dev/null +++ b/internal/forge/forgejo/highvalue_test.go @@ -0,0 +1,55 @@ +package forgejo + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +func TestCommitFilesToBranchAndReview(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"name": "r", "full_name": "o/r", "default_branch": "main", "owner": map[string]any{"login": "o"}}) + }) + mux.HandleFunc("/api/v1/repos/o/r/contents/a.txt", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + http.NotFound(w, r) + return + } + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"content": map[string]any{"path": "a.txt"}}) + }) + mux.HandleFunc("/api/v1/repos/o/r/pulls/1/reviews", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(map[string]any{"id": 9}) + return + } + _ = json.NewEncoder(w).Encode([]map[string]any{{"id": 9, "state": "APPROVED", "user": map[string]any{"login": "u"}, "body": "ok"}}) + }) + mux.HandleFunc("/api/v1/repos/o/r/branch_protections/main", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"branch_name": "main", "enable_push": false}) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + c := New("t", WithBaseURL(srv.URL+"/api/v1")) + ok, err := c.CommitFilesToBranch(context.Background(), "o", "r", "main", "msg", []forge.TreeFile{{Path: "a.txt", Content: []byte("hi")}}) + if err != nil || !ok { + t.Fatalf("commit: ok=%v err=%v", ok, err) + } + if err := c.CreatePullRequestReview(context.Background(), "o", "r", 1, "APPROVE", "lgtm", "", nil); err != nil { + t.Fatal(err) + } + revs, err := c.ListPullRequestReviews(context.Background(), "o", "r", 1) + if err != nil || len(revs) != 1 { + t.Fatalf("reviews=%v err=%v", revs, err) + } + prot, err := c.IsProtectedBranch(context.Background(), "o", "r", "main") + if err != nil || !prot { + t.Fatalf("prot=%v err=%v", prot, err) + } +} diff --git a/internal/forge/forgejo/live_smoke_test.go b/internal/forge/forgejo/live_smoke_test.go new file mode 100644 index 0000000000..e3b750f896 --- /dev/null +++ b/internal/forge/forgejo/live_smoke_test.go @@ -0,0 +1,33 @@ +//go:build live_forgejo + +package forgejo + +import ( + "context" + "os" + "testing" +) + +func TestLiveForgejoSmoke(t *testing.T) { + tok := os.Getenv("FORGEJO_TOKEN") + if tok == "" { + t.Skip("FORGEJO_TOKEN not set") + } + c := New(tok, WithBaseURL("https://git.forge.internal/api/v1")) + u, err := c.GetAuthenticatedUser(context.Background()) + if err != nil { + t.Fatal(err) + } + r, err := c.GetRepo(context.Background(), "forgeops-ai", "forge-platform") + if err != nil { + t.Fatal(err) + } + repos, err := c.ListOrgRepos(context.Background(), "forgeops-ai", true) + if err != nil { + t.Fatal(err) + } + t.Logf("user=%s repo=%s count=%d", u, r.FullName, len(repos)) + if r.FullName == "" || len(repos) < 1 { + t.Fatal("unexpected empty") + } +} diff --git a/internal/forge/forgejo/repos.go b/internal/forge/forgejo/repos.go new file mode 100644 index 0000000000..e0866a858f --- /dev/null +++ b/internal/forge/forgejo/repos.go @@ -0,0 +1,515 @@ +package forgejo + +import ( + "context" + "encoding/base64" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +func mapRepo(r apiRepo) forge.Repository { + return forge.Repository{ + ID: r.ID, + Name: r.Name, + FullName: r.FullName, + Description: r.Description, + Private: r.Private, + Fork: r.Fork, + Archived: r.Archived, + DefaultBranch: r.DefaultBranch, + } +} + +// GetAuthenticatedUserIdentity implements forge.Client. +func (c *LiveClient) GetAuthenticatedUserIdentity(ctx context.Context) (*forge.UserIdentity, error) { + var u apiUser + if _, err := c.do(ctx, http.MethodGet, "/user", nil, &u); err != nil { + return nil, err + } + name := u.FullName + if name == "" { + name = u.Login + } + email := u.Email + if email == "" { + email = u.Login + "@users.noreply.local" + } + return &forge.UserIdentity{Name: name, Email: email}, nil +} + +type apiContents struct { + Content string `json:"content"` + Encoding string `json:"encoding"` + SHA string `json:"sha"` + Type string `json:"type"` + Path string `json:"path"` + Name string `json:"name"` +} + +func (c *LiveClient) getContents(ctx context.Context, owner, repo, path, ref string) (*apiContents, error) { + p := "/repos/" + escapePath(owner, repo) + "/contents/" + strings.TrimPrefix(path, "/") + if ref != "" { + p += "?ref=" + url.QueryEscape(ref) + } + var out apiContents + if _, err := c.do(ctx, http.MethodGet, p, nil, &out); err != nil { + return nil, err + } + return &out, nil +} + +func decodeContent(c *apiContents) ([]byte, error) { + if c.Encoding == "base64" || c.Encoding == "" { + // Forgejo returns base64, possibly wrapped with newlines. + raw := strings.ReplaceAll(c.Content, "\n", "") + return base64.StdEncoding.DecodeString(raw) + } + return []byte(c.Content), nil +} + +// GetFileContent implements forge.Client. +func (c *LiveClient) GetFileContent(ctx context.Context, owner, repo, path string) ([]byte, error) { + ct, err := c.getContents(ctx, owner, repo, path, "") + if err != nil { + return nil, err + } + return decodeContent(ct) +} + +// GetFileContentAtRef implements forge.Client. +func (c *LiveClient) GetFileContentAtRef(ctx context.Context, owner, repo, path, ref string) ([]byte, error) { + ct, err := c.getContents(ctx, owner, repo, path, ref) + if err != nil { + return nil, err + } + return decodeContent(ct) +} + +func (c *LiveClient) putFile(ctx context.Context, owner, repo, path, message, branch string, content []byte, sha string) error { + payload := map[string]any{ + "content": base64.StdEncoding.EncodeToString(content), + "message": message, + } + if branch != "" { + payload["branch"] = branch + } + if sha != "" { + payload["sha"] = sha + } + p := "/repos/" + escapePath(owner, repo) + "/contents/" + strings.TrimPrefix(path, "/") + _, err := c.do(ctx, http.MethodPut, p, payload, nil) + return err +} + +// CreateFile implements forge.Client. +func (c *LiveClient) CreateFile(ctx context.Context, owner, repo, path, message string, content []byte) error { + return c.putFile(ctx, owner, repo, path, message, "", content, "") +} + +// CreateOrUpdateFile implements forge.Client. +func (c *LiveClient) CreateOrUpdateFile(ctx context.Context, owner, repo, path, message string, content []byte) error { + sha := "" + if ct, err := c.getContents(ctx, owner, repo, path, ""); err == nil { + sha = ct.SHA + } + return c.putFile(ctx, owner, repo, path, message, "", content, sha) +} + +// CreateFileOnBranch implements forge.Client. +func (c *LiveClient) CreateFileOnBranch(ctx context.Context, owner, repo, branch, path, message string, content []byte) error { + return c.putFile(ctx, owner, repo, path, message, branch, content, "") +} + +// CreateOrUpdateFileOnBranch implements forge.Client. +func (c *LiveClient) CreateOrUpdateFileOnBranch(ctx context.Context, owner, repo, branch, path, message string, content []byte) error { + sha := "" + if ct, err := c.getContents(ctx, owner, repo, path, branch); err == nil { + sha = ct.SHA + } + return c.putFile(ctx, owner, repo, path, message, branch, content, sha) +} + +// DeleteFile implements forge.Client. +func (c *LiveClient) DeleteFile(ctx context.Context, owner, repo, path, message string) error { + ct, err := c.getContents(ctx, owner, repo, path, "") + if err != nil { + return err + } + payload := map[string]any{"message": message, "sha": ct.SHA} + p := "/repos/" + escapePath(owner, repo) + "/contents/" + strings.TrimPrefix(path, "/") + _, err = c.do(ctx, http.MethodDelete, p, payload, nil) + return err +} + +// ListDirectoryContents implements forge.Client. +func (c *LiveClient) ListDirectoryContents(ctx context.Context, owner, repo, path, ref string, recursive bool) ([]forge.DirectoryEntry, error) { + _ = recursive // Forgejo contents API is non-recursive; callers may walk. + p := "/repos/" + escapePath(owner, repo) + "/contents/" + strings.TrimPrefix(path, "/") + if ref != "" { + p += "?ref=" + url.QueryEscape(ref) + } + var raw []apiContents + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.DirectoryEntry, 0, len(raw)) + for _, e := range raw { + typ := e.Type + if typ == "blob" { + typ = "file" + } + if typ == "tree" { + typ = "dir" + } + out = append(out, forge.DirectoryEntry{Path: e.Path, Type: typ}) + } + return out, nil +} + +// ListRepositoryFiles implements forge.Client via git trees when available. +func (c *LiveClient) ListRepositoryFiles(ctx context.Context, owner, repo string) ([]string, error) { + r, err := c.GetRepo(ctx, owner, repo) + if err != nil { + return nil, err + } + ref := r.DefaultBranch + var tree struct { + Tree []struct { + Path string `json:"path"` + Type string `json:"type"` + } `json:"tree"` + Truncated bool `json:"truncated"` + } + p := "/repos/" + escapePath(owner, repo) + "/git/trees/" + url.PathEscape(ref) + "?recursive=true" + if _, err := c.do(ctx, http.MethodGet, p, nil, &tree); err != nil { + return nil, err + } + out := make([]string, 0, len(tree.Tree)) + for _, t := range tree.Tree { + if t.Type == "blob" { + out = append(out, t.Path) + } + } + return out, nil +} + +type apiBranch struct { + Name string `json:"name"` + Commit struct { + ID string `json:"id"` + } `json:"commit"` +} + +// GetBranchRef implements forge.Client. +func (c *LiveClient) GetBranchRef(ctx context.Context, owner, repo, branch string) (string, error) { + var b apiBranch + p := "/repos/" + escapePath(owner, repo) + "/branches/" + url.PathEscape(branch) + if _, err := c.do(ctx, http.MethodGet, p, nil, &b); err != nil { + return "", err + } + return b.Commit.ID, nil +} + +// GetRef implements forge.Client. +func (c *LiveClient) GetRef(ctx context.Context, owner, repo, ref string) (string, error) { + ref = strings.TrimPrefix(ref, "refs/heads/") + return c.GetBranchRef(ctx, owner, repo, ref) +} + +// CreateBranch implements forge.Client. +func (c *LiveClient) CreateBranch(ctx context.Context, owner, repo, branchName string) error { + r, err := c.GetRepo(ctx, owner, repo) + if err != nil { + return err + } + sha, err := c.GetBranchRef(ctx, owner, repo, r.DefaultBranch) + if err != nil { + return err + } + return c.CreateBranchFromSHA(ctx, owner, repo, branchName, sha) +} + +// CreateBranchFromSHA implements forge.Client. +func (c *LiveClient) CreateBranchFromSHA(ctx context.Context, owner, repo, branch, sha string) error { + payload2 := map[string]any{ + "ref": "refs/heads/" + branch, + "sha": sha, + } + _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/git/refs", payload2, nil) + if err == nil { + return nil + } + payload := map[string]any{"new_branch_name": branch, "old_ref_name": sha} + _, err2 := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/branches", payload, nil) + if err2 != nil { + return fmt.Errorf("create branch: refs=%v branches=%v", err, err2) + } + return nil +} + +// DeleteBranch implements forge.Client. +func (c *LiveClient) DeleteBranch(ctx context.Context, owner, repo, branch string) error { + _, err := c.do(ctx, http.MethodDelete, "/repos/"+escapePath(owner, repo)+"/branches/"+url.PathEscape(branch), nil, nil) + return err +} + +// DeleteRef implements forge.Client. +func (c *LiveClient) DeleteRef(ctx context.Context, owner, repo, ref string) error { + ref = strings.TrimPrefix(ref, "refs/heads/") + return c.DeleteBranch(ctx, owner, repo, ref) +} + +type apiPR struct { + ID int64 `json:"id"` + Number int `json:"number"` + Title string `json:"title"` + URL string `json:"html_url"` + State string `json:"state"` + Head struct { + Ref string `json:"ref"` + SHA string `json:"sha"` + Repo apiRepo `json:"repo"` + } `json:"head"` + Base struct { + Ref string `json:"ref"` + Repo apiRepo `json:"repo"` + } `json:"base"` + User apiUser `json:"user"` +} + +func mapPR(p apiPR) forge.ChangeProposal { + return forge.ChangeProposal{ + URL: p.URL, + Title: p.Title, + Number: p.Number, + ID: p.ID, + Head: p.Head.Ref, + HeadRepo: p.Head.Repo.FullName, + Base: p.Base.Ref, + Author: p.User.Login, + } +} + +// CreateChangeProposal implements forge.Client. +func (c *LiveClient) CreateChangeProposal(ctx context.Context, owner, repo, title, body, head, base string) (*forge.ChangeProposal, error) { + payload := map[string]any{ + "title": title, + "body": body, + "head": head, + "base": base, + } + var pr apiPR + if _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/pulls", payload, &pr); err != nil { + return nil, err + } + m := mapPR(pr) + return &m, nil +} + +// ListRepoPullRequests implements forge.Client. +func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo string) ([]forge.ChangeProposal, error) { + var raw []apiPR + if _, err := c.do(ctx, http.MethodGet, "/repos/"+escapePath(owner, repo)+"/pulls?state=open&limit=50", nil, &raw); err != nil { + return nil, err + } + out := make([]forge.ChangeProposal, 0, len(raw)) + for _, p := range raw { + out = append(out, mapPR(p)) + } + return out, nil +} + +// CloseChangeProposal implements forge.Client. +func (c *LiveClient) CloseChangeProposal(ctx context.Context, owner, repo string, number int) error { + payload := map[string]any{"state": "closed"} + _, err := c.do(ctx, http.MethodPatch, "/repos/"+escapePath(owner, repo)+"/pulls/"+strconv.Itoa(number), payload, nil) + return err +} + +// GetPullRequestInfo implements forge.Client. +func (c *LiveClient) GetPullRequestInfo(ctx context.Context, owner, repo string, number int) (*forge.PullRequestInfo, error) { + var pr apiPR + if _, err := c.do(ctx, http.MethodGet, "/repos/"+escapePath(owner, repo)+"/pulls/"+strconv.Itoa(number), nil, &pr); err != nil { + return nil, err + } + return &forge.PullRequestInfo{ + Number: pr.Number, + HTMLURL: pr.URL, + HeadRepo: pr.Head.Repo.FullName, + BaseRepo: pr.Base.Repo.FullName, + HeadRef: pr.Head.Ref, + BaseRef: pr.Base.Ref, + HeadSHA: pr.Head.SHA, + AuthorID: strconv.FormatInt(pr.User.ID, 10), + IsFork: pr.Head.Repo.FullName != pr.Base.Repo.FullName, + }, nil +} + +// GetPullRequestHeadSHA implements forge.Client. +func (c *LiveClient) GetPullRequestHeadSHA(ctx context.Context, owner, repo string, number int) (string, error) { + info, err := c.GetPullRequestInfo(ctx, owner, repo, number) + if err != nil { + return "", err + } + return info.HeadSHA, nil +} + +// ListPullRequestFiles implements forge.Client. +func (c *LiveClient) ListPullRequestFiles(ctx context.Context, owner, repo string, number int) ([]string, error) { + var files []struct { + Filename string `json:"filename"` + } + if _, err := c.do(ctx, http.MethodGet, "/repos/"+escapePath(owner, repo)+"/pulls/"+strconv.Itoa(number)+"/files", nil, &files); err != nil { + return nil, err + } + out := make([]string, 0, len(files)) + for _, f := range files { + out = append(out, f.Filename) + } + return out, nil +} + +// MergeChangeProposal implements forge.Client. +func (c *LiveClient) MergeChangeProposal(ctx context.Context, owner, repo string, number int) error { + payload := map[string]any{"Do": "merge"} + _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/pulls/"+strconv.Itoa(number)+"/merge", payload, nil) + return err +} + +type apiIssue struct { + ID int64 `json:"id"` + Number int `json:"number"` + Title string `json:"title"` + Body string `json:"body"` + State string `json:"state"` + Pull bool `json:"pull_request"` + User apiUser `json:"user"` +} + +// CreateIssue implements forge.Client. Labels are applied best-effort after +// create so a missing label cannot block issue creation. +func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body string, labels ...string) (*forge.Issue, error) { + payload := map[string]any{"title": title, "body": body} + var iss apiIssue + if _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/issues", payload, &iss); err != nil { + return nil, err + } + if len(labels) > 0 { + _ = c.AddIssueLabels(ctx, owner, repo, iss.Number, labels...) + } + return &forge.Issue{ID: iss.ID, Number: iss.Number, Title: iss.Title, Body: iss.Body}, nil +} + +// GetIssue implements forge.Client. +func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number int) (*forge.Issue, error) { + var iss apiIssue + if _, err := c.do(ctx, http.MethodGet, "/repos/"+escapePath(owner, repo)+"/issues/"+strconv.Itoa(number), nil, &iss); err != nil { + return nil, err + } + return &forge.Issue{ID: iss.ID, Number: iss.Number, Title: iss.Title, Body: iss.Body, IsPullRequest: iss.Pull}, nil +} + +// CloseIssue implements forge.Client. +func (c *LiveClient) CloseIssue(ctx context.Context, owner, repo string, number int) error { + payload := map[string]any{"state": "closed"} + _, err := c.do(ctx, http.MethodPatch, "/repos/"+escapePath(owner, repo)+"/issues/"+strconv.Itoa(number), payload, nil) + return err +} + +// ListOpenIssues implements forge.Client. +func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, labels ...string) ([]forge.Issue, error) { + p := "/repos/" + escapePath(owner, repo) + "/issues?state=open&type=issues&limit=50" + if len(labels) > 0 { + p += "&labels=" + url.QueryEscape(strings.Join(labels, ",")) + } + var raw []apiIssue + if _, err := c.do(ctx, http.MethodGet, p, nil, &raw); err != nil { + return nil, err + } + out := make([]forge.Issue, 0, len(raw)) + for _, iss := range raw { + if iss.Pull { + continue + } + out = append(out, forge.Issue{ID: iss.ID, Number: iss.Number, Title: iss.Title, Body: iss.Body}) + } + return out, nil +} + +// EnsureLabel implements forge.Client. +func (c *LiveClient) EnsureLabel(ctx context.Context, owner, repo, name string) error { + payload := map[string]any{"name": name, "color": "#ededed"} + _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/labels", payload, nil) + if err == nil || forge.IsConflict(err) { + return nil + } + // already exists often returns 422 + if strings.Contains(err.Error(), "422") || strings.Contains(strings.ToLower(err.Error()), "already") { + return nil + } + return err +} + +// AddIssueLabels implements forge.Client. +func (c *LiveClient) AddIssueLabels(ctx context.Context, owner, repo string, number int, labels ...string) error { + for _, l := range labels { + _ = c.EnsureLabel(ctx, owner, repo, l) + } + payload := map[string]any{"labels": labels} + _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/issues/"+strconv.Itoa(number)+"/labels", payload, nil) + return err +} + +type apiComment struct { + ID int64 `json:"id"` + Body string `json:"body"` + User apiUser `json:"user"` +} + +// CreateIssueComment implements forge.Client. +func (c *LiveClient) CreateIssueComment(ctx context.Context, owner, repo string, number int, body string) (*forge.IssueComment, error) { + payload := map[string]any{"body": body} + var cm apiComment + if _, err := c.do(ctx, http.MethodPost, "/repos/"+escapePath(owner, repo)+"/issues/"+strconv.Itoa(number)+"/comments", payload, &cm); err != nil { + return nil, err + } + return &forge.IssueComment{ID: int(cm.ID), Body: cm.Body, Author: cm.User.Login}, nil +} + +// ListIssueComments implements forge.Client. +func (c *LiveClient) ListIssueComments(ctx context.Context, owner, repo string, number int) ([]forge.IssueComment, error) { + var raw []apiComment + if _, err := c.do(ctx, http.MethodGet, "/repos/"+escapePath(owner, repo)+"/issues/"+strconv.Itoa(number)+"/comments", nil, &raw); err != nil { + return nil, err + } + out := make([]forge.IssueComment, 0, len(raw)) + for _, cm := range raw { + out = append(out, forge.IssueComment{ID: int(cm.ID), Body: cm.Body, Author: cm.User.Login}) + } + return out, nil +} + +// CompareCommits implements forge.Client. +func (c *LiveClient) CompareCommits(ctx context.Context, owner, repo, base, head string) (status string, err error) { + var cmp struct { + Status string `json:"status"` + TotalCommits int `json:"total_commits"` + } + p := "/repos/" + escapePath(owner, repo) + "/compare/" + url.PathEscape(base) + "..." + url.PathEscape(head) + if _, err := c.do(ctx, http.MethodGet, p, nil, &cmp); err != nil { + return "", err + } + if cmp.Status != "" { + return cmp.Status, nil + } + // Forgejo/Gitea often omit GitHub-style status; derive a coarse signal. + if cmp.TotalCommits == 0 { + return "identical", nil + } + return "ahead", nil +} diff --git a/internal/forge/forgejo/stubs.go b/internal/forge/forgejo/stubs.go new file mode 100644 index 0000000000..2801f77517 --- /dev/null +++ b/internal/forge/forgejo/stubs.go @@ -0,0 +1,198 @@ +package forgejo + +import ( + "context" + "fmt" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +// DeleteProjectServiceAccount is not supported on Forgejo. +func (c *LiveClient) DeleteProjectServiceAccount(ctx context.Context, owner, repo string, userID int) error { + return fmt.Errorf("forgejo DeleteProjectServiceAccount: %w", forge.ErrNotSupported) +} + +// GetOrgPlan is not supported on Forgejo. +func (c *LiveClient) GetOrgPlan(ctx context.Context, org string) (string, error) { + return "", fmt.Errorf("forgejo GetOrgPlan: %w", forge.ErrNotSupported) +} + +// MinimizeComment is not supported on Forgejo (no GitHub minimize API). +func (c *LiveClient) MinimizeComment(ctx context.Context, nodeID, reason string) error { + return fmt.Errorf("forgejo MinimizeComment: %w", forge.ErrNotSupported) +} + +// ListIssueLabelEvents is not supported on Forgejo. +func (c *LiveClient) ListIssueLabelEvents(ctx context.Context, owner, repo string, number int) ([]forge.IssueLabelEvent, error) { + return nil, fmt.Errorf("forgejo ListIssueLabelEvents: %w", forge.ErrNotSupported) +} + +// GetWorkflowRunAnnotations is not supported on Forgejo. +func (c *LiveClient) GetWorkflowRunAnnotations(ctx context.Context, owner, repo string, runID int) ([]forge.Annotation, error) { + return nil, fmt.Errorf("forgejo GetWorkflowRunAnnotations: %w", forge.ErrNotSupported) +} + +// ListProtectedTags is not supported on Forgejo. +func (c *LiveClient) ListProtectedTags(ctx context.Context, owner, repo string) ([]string, error) { + return nil, fmt.Errorf("forgejo ListProtectedTags: %w", forge.ErrNotSupported) +} + +// GrantProtectedBranchMergeUser is not supported on Forgejo. +func (c *LiveClient) GrantProtectedBranchMergeUser(ctx context.Context, owner, repo, branch string, userID int) error { + return fmt.Errorf("forgejo GrantProtectedBranchMergeUser: %w", forge.ErrNotSupported) +} + +// RevokeProtectedBranchMergeUserEntry is not supported on Forgejo. +func (c *LiveClient) RevokeProtectedBranchMergeUserEntry(ctx context.Context, owner, repo, branch string, entryID, userID int) error { + return fmt.Errorf("forgejo RevokeProtectedBranchMergeUserEntry: %w", forge.ErrNotSupported) +} + +// OrgSecretExists is not yet implemented for Forgejo. +func (c *LiveClient) OrgSecretExists(ctx context.Context, org, name string) (bool, error) { + return false, fmt.Errorf("forgejo OrgSecretExists: %w", forge.ErrNotSupported) +} + +// DeleteOrgSecret is not yet implemented for Forgejo. +func (c *LiveClient) DeleteOrgSecret(ctx context.Context, org, name string) error { + return fmt.Errorf("forgejo DeleteOrgSecret: %w", forge.ErrNotSupported) +} + +// CreateOrUpdateOrgVariableAll is not yet implemented for Forgejo. +func (c *LiveClient) CreateOrUpdateOrgVariableAll(ctx context.Context, org, name, value string) error { + return fmt.Errorf("forgejo CreateOrUpdateOrgVariableAll: %w", forge.ErrNotSupported) +} + +// GetOrgVariable is not yet implemented for Forgejo. +func (c *LiveClient) GetOrgVariable(ctx context.Context, org, name string) (value string, exists bool, err error) { + return "", false, fmt.Errorf("forgejo GetOrgVariable: %w", forge.ErrNotSupported) +} + +// ListOrgVariables is not yet implemented for Forgejo. +func (c *LiveClient) ListOrgVariables(ctx context.Context, org string) ([]forge.OrgVariable, error) { + return nil, fmt.Errorf("forgejo ListOrgVariables: %w", forge.ErrNotSupported) +} + +// ListInheritedRepoVariables is not yet implemented for Forgejo. +func (c *LiveClient) ListInheritedRepoVariables(ctx context.Context, owner, repo string) ([]forge.OrgVariable, error) { + return nil, fmt.Errorf("forgejo ListInheritedRepoVariables: %w", forge.ErrNotSupported) +} + +// ListInstanceVariables is not yet implemented for Forgejo. +func (c *LiveClient) ListInstanceVariables(ctx context.Context) ([]forge.OrgVariable, error) { + return nil, fmt.Errorf("forgejo ListInstanceVariables: %w", forge.ErrNotSupported) +} + +// DeleteOrgVariable is not yet implemented for Forgejo. +func (c *LiveClient) DeleteOrgVariable(ctx context.Context, org, name string) error { + return fmt.Errorf("forgejo DeleteOrgVariable: %w", forge.ErrNotSupported) +} + +// CreatePipeline is GitLab-only. +func (c *LiveClient) CreatePipeline(ctx context.Context, owner, repo, ref string, variables map[string]string) (*forge.Pipeline, error) { + return nil, fmt.Errorf("forgejo CreatePipeline: %w", forge.ErrNotSupported) +} + +// CreatePipelineWithInputs is GitLab-only. +func (c *LiveClient) CreatePipelineWithInputs(ctx context.Context, owner, repo, ref string, inputs map[string]forge.PipelineInputValue) (*forge.Pipeline, error) { + return nil, fmt.Errorf("forgejo CreatePipelineWithInputs: %w", forge.ErrNotSupported) +} + +// CreatePipelineSchedule is GitLab-only. +func (c *LiveClient) CreatePipelineSchedule(ctx context.Context, owner, repo, ref, description, cron string, variables map[string]string) (int64, error) { + return 0, fmt.Errorf("forgejo CreatePipelineSchedule: %w", forge.ErrNotSupported) +} + +// CreatePipelineScheduleWithActive is GitLab-only. +func (c *LiveClient) CreatePipelineScheduleWithActive(ctx context.Context, owner, repo, ref, description, cron string, variables map[string]string, active bool) (int64, error) { + return 0, fmt.Errorf("forgejo CreatePipelineScheduleWithActive: %w", forge.ErrNotSupported) +} + +// DeletePipelineSchedule is GitLab-only. +func (c *LiveClient) DeletePipelineSchedule(ctx context.Context, owner, repo string, scheduleID int64) error { + return fmt.Errorf("forgejo DeletePipelineSchedule: %w", forge.ErrNotSupported) +} + +// GetPipelineSchedule is GitLab-only. +func (c *LiveClient) GetPipelineSchedule(ctx context.Context, owner, repo string, scheduleID int64) (*forge.PipelineSchedule, error) { + return nil, fmt.Errorf("forgejo GetPipelineSchedule: %w", forge.ErrNotSupported) +} + +// ListPipelineSchedules is GitLab-only. +func (c *LiveClient) ListPipelineSchedules(ctx context.Context, owner, repo string) ([]forge.PipelineSchedule, error) { + return nil, fmt.Errorf("forgejo ListPipelineSchedules: %w", forge.ErrNotSupported) +} + +// UpdatePipelineSchedule is GitLab-only. +func (c *LiveClient) UpdatePipelineSchedule(ctx context.Context, owner, repo string, scheduleID int64, active bool) error { + return fmt.Errorf("forgejo UpdatePipelineSchedule: %w", forge.ErrNotSupported) +} + +// UpdateCIVariable is GitLab-only. +func (c *LiveClient) UpdateCIVariable(ctx context.Context, owner, repo, name, value string, protected bool) error { + return fmt.Errorf("forgejo UpdateCIVariable: %w", forge.ErrNotSupported) +} + +// CreateProtectedCIVariable is GitLab-only. +func (c *LiveClient) CreateProtectedCIVariable(ctx context.Context, owner, repo, name, value string) error { + return fmt.Errorf("forgejo CreateProtectedCIVariable: %w", forge.ErrNotSupported) +} + +// CreatePipelineTriggerToken is GitLab-only. +func (c *LiveClient) CreatePipelineTriggerToken(ctx context.Context, owner, repo, description string) (*forge.PipelineTriggerToken, error) { + return nil, fmt.Errorf("forgejo CreatePipelineTriggerToken: %w", forge.ErrNotSupported) +} + +// ListPipelineTriggerTokens is GitLab-only. +func (c *LiveClient) ListPipelineTriggerTokens(ctx context.Context, owner, repo string) ([]forge.PipelineTriggerToken, error) { + return nil, fmt.Errorf("forgejo ListPipelineTriggerTokens: %w", forge.ErrNotSupported) +} + +// RevokePipelineTriggerToken is GitLab-only. +func (c *LiveClient) RevokePipelineTriggerToken(ctx context.Context, owner, repo string, tokenID int64) error { + return fmt.Errorf("forgejo RevokePipelineTriggerToken: %w", forge.ErrNotSupported) +} + +// GetProjectMemberAccessLevel is GitLab-only. +func (c *LiveClient) GetProjectMemberAccessLevel(ctx context.Context, owner, repo string, userID int64) (int, error) { + return 0, fmt.Errorf("forgejo GetProjectMemberAccessLevel: %w", forge.ErrNotSupported) +} + +// CreateProjectHook is not yet implemented for Forgejo. +func (c *LiveClient) CreateProjectHook(ctx context.Context, owner, repo string, hook forge.ProjectHook) (*forge.ProjectHook, error) { + return nil, fmt.Errorf("forgejo CreateProjectHook: %w", forge.ErrNotSupported) +} + +// ListProjectHooks is not yet implemented for Forgejo. +func (c *LiveClient) ListProjectHooks(ctx context.Context, owner, repo string) ([]forge.ProjectHook, error) { + return nil, fmt.Errorf("forgejo ListProjectHooks: %w", forge.ErrNotSupported) +} + +// UpdateProjectHook is not yet implemented for Forgejo. +func (c *LiveClient) UpdateProjectHook(ctx context.Context, owner, repo string, hookID int64, hook forge.ProjectHook) (*forge.ProjectHook, error) { + return nil, fmt.Errorf("forgejo UpdateProjectHook: %w", forge.ErrNotSupported) +} + +// DeleteProjectHook is not yet implemented for Forgejo. +func (c *LiveClient) DeleteProjectHook(ctx context.Context, owner, repo string, hookID int64) error { + return fmt.Errorf("forgejo DeleteProjectHook: %w", forge.ErrNotSupported) +} + +// GetPipelineVariablesMinimumOverrideRole is GitLab-only. +func (c *LiveClient) GetPipelineVariablesMinimumOverrideRole(ctx context.Context, owner, repo string) (string, error) { + return "", fmt.Errorf("forgejo GetPipelineVariablesMinimumOverrideRole: %w", forge.ErrNotSupported) +} + +// SetPipelineVariablesMinimumOverrideRole is GitLab-only. +func (c *LiveClient) SetPipelineVariablesMinimumOverrideRole(ctx context.Context, owner, repo, role string) error { + return fmt.Errorf("forgejo SetPipelineVariablesMinimumOverrideRole: %w", forge.ErrNotSupported) +} + +// GetJobTokenRepositoryPushAllowed is GitLab-only. +func (c *LiveClient) GetJobTokenRepositoryPushAllowed(ctx context.Context, owner, repo string) (bool, error) { + return false, fmt.Errorf("forgejo GetJobTokenRepositoryPushAllowed: %w", forge.ErrNotSupported) +} + +// GetPushRuleBranchNameRegex is GitLab-only. +func (c *LiveClient) GetPushRuleBranchNameRegex(ctx context.Context, owner, repo string) (string, error) { + return "", fmt.Errorf("forgejo GetPushRuleBranchNameRegex: %w", forge.ErrNotSupported) +} diff --git a/internal/harness/forge.go b/internal/harness/forge.go index d9c1ca6477..191a17c694 100644 --- a/internal/harness/forge.go +++ b/internal/harness/forge.go @@ -47,6 +47,8 @@ var validForgeKeys = map[string]bool{ // JIRA issues. The code agent remains blocked on a longer-term forge // abstraction design (see https://github.com/fullsend-ai/fullsend/pull/6237). "jira": true, + // Forgejo/Gitea API client (ForgeOps FACTORY-FULLSEND-FORGEJO-CLIENT-001). + "forgejo": true, } // ValidForgePlatform reports whether platform is a recognized forge key. diff --git a/internal/harness/forge_test.go b/internal/harness/forge_test.go index 64b4f526a1..5ecaa46b83 100644 --- a/internal/harness/forge_test.go +++ b/internal/harness/forge_test.go @@ -494,7 +494,7 @@ func TestValidate_ForgeUnrecognizedKey(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "unrecognized key") assert.Contains(t, err.Error(), "gihub") - assert.Contains(t, err.Error(), "valid: github, gitlab, jira") + assert.Contains(t, err.Error(), "valid: forgejo, github, gitlab, jira") } func TestValidateForge_JiraBlock(t *testing.T) { diff --git a/internal/harness/harness_test.go b/internal/harness/harness_test.go index b5a3f5be31..9416c74f7a 100644 --- a/internal/harness/harness_test.go +++ b/internal/harness/harness_test.go @@ -2291,6 +2291,7 @@ func TestValidForgePlatform(t *testing.T) { assert.True(t, ValidForgePlatform("github")) assert.True(t, ValidForgePlatform("gitlab")) assert.True(t, ValidForgePlatform("jira")) + assert.True(t, ValidForgePlatform("forgejo")) assert.False(t, ValidForgePlatform("bitbucket")) assert.False(t, ValidForgePlatform("")) } diff --git a/internal/repos/forge_config.go b/internal/repos/forge_config.go index c03d213ff0..0d4a25f227 100644 --- a/internal/repos/forge_config.go +++ b/internal/repos/forge_config.go @@ -97,6 +97,9 @@ func ForgeConfigFor(forgeName string) ForgeConfig { switch forgeName { case ForgeGitLab: return GitLabForgeConfig() + case ForgeForgejo: + // Forgejo Actions is GitHub Actions–compatible; reuse GitHub shim paths. + return GitHubForgeConfig() default: return GitHubForgeConfig() } diff --git a/internal/repos/manifest.go b/internal/repos/manifest.go index 927c4e1c4f..ddb4d877df 100644 --- a/internal/repos/manifest.go +++ b/internal/repos/manifest.go @@ -33,8 +33,9 @@ const maxManifestBytes = 1 << 20 // 1 MB // Forge type constants used in the manifest's platform sections. const ( - ForgeGitHub = "github" - ForgeGitLab = "gitlab" + ForgeGitHub = "github" + ForgeGitLab = "gitlab" + ForgeForgejo = "forgejo" ) // Mint mode constants control the default mint URL for GitHub repos. @@ -95,8 +96,9 @@ type InferenceSettings struct { // validForges is the set of accepted forge values. var validForges = map[string]bool{ - ForgeGitHub: true, - ForgeGitLab: true, + ForgeGitHub: true, + ForgeGitLab: true, + ForgeForgejo: true, // API client MVP (FACTORY-FULLSEND-FORGEJO-CLIENT-001); install/CI parity still GitHub/GitLab } // IsValidForge reports whether the given forge name is supported.