From 5c5d2fc6ead338bbb40606e23684151320a4c5e8 Mon Sep 17 00:00:00 2001 From: adamkaabyia Date: Wed, 22 Jul 2026 12:51:07 +0300 Subject: [PATCH] feat: add per-project GitLab hosting support Enable GitLab as a VCS backend alongside GitHub, selectable per workspace via the `hosting: gitlab` configuration field. A hosting router dispatches operations to the correct provider based on owner/repo mapping. Key changes: - Extract provider-agnostic git operations into shared GitOps helper - Add GitLabServiceImpl (PAT auth, MR creation, pipeline status, notes) - Add hosting router that satisfies all consumer interfaces - Make GitHub validation conditional (only when workspaces use GitHub) - Add GitLab config struct with environment variable bindings - Add comprehensive tests for GitLab service, router, and shared GitOps - Add docs/gitlab-support.md deployment and usage guide Design: - GitLab commits via local git push (vs GitHub's Git Data API) - PAT/Project/Group Access Token authentication - Workspace-level hosting field with fallback to GitHub (backward compat) - Zero changes to existing GitHub-only deployments --- AGENTS.md | 10 +- config.example.yaml | 82 +++ docs/gitlab-support.md | 379 +++++++++++++ main.go | 68 ++- models/config.go | 152 +++++- services/github.go | 406 +------------- services/gitlab.go | 935 ++++++++++++++++++++++++++++++++ services/gitlab_test.go | 346 ++++++++++++ services/gitops.go | 476 ++++++++++++++++ services/gitops_test.go | 126 +++++ services/hosting/router.go | 302 +++++++++++ services/hosting/router_test.go | 282 ++++++++++ 12 files changed, 3139 insertions(+), 425 deletions(-) create mode 100644 docs/gitlab-support.md create mode 100644 services/gitlab.go create mode 100644 services/gitlab_test.go create mode 100644 services/gitops.go create mode 100644 services/gitops_test.go create mode 100644 services/hosting/router.go create mode 100644 services/hosting/router_test.go diff --git a/AGENTS.md b/AGENTS.md index 6303ff2..e45f6c0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,8 @@ The application uses consumer-defined interfaces and clear package boundaries: - **`commentfilter/`** — Shared bot-loop prevention (ignored users, known bots, thread depth limits) - **`recovery/`** — `StartupRunner` for crash recovery (orphan container cleanup, stuck ticket reset, workspace TTL) - **`costtracker/`** — `FileTracker` for daily AI session cost tracking with budget enforcement -- **`services/`** — Infrastructure implementations: `JiraService` (Jira REST API), `GitHubService` (GitHub App auth, Git Data API, PR operations) +- **`services/`** — Infrastructure implementations: `JiraService` (Jira REST API), `GitHubService` (GitHub App auth, Git Data API, PR operations), `GitLabService` (GitLab PAT auth, MR operations), `GitOps` (shared provider-agnostic git commands) +- **`services/hosting/`** — `Router` that dispatches VCS operations to the correct backend (GitHub or GitLab) based on owner/repo mapping from project config - **`models/`** — Configuration (`Config`), Jira API types, domain types (`WorkItem`, `SearchCriteria`, `ProjectSettings`) ### Design Principles @@ -50,6 +51,8 @@ Key configuration features: - `GetProjectConfigForTicket()` retrieves the appropriate project config based on ticket key - `StatusTransitions` maps ticket types to their workflow statuses (todo, in_progress, in_review, and optionally merged) - **Workspaces** group one or more repos into a named working environment. A single-repo project is a workspace with one entry. Multi-repo workspaces clone all repos into subdirectories and run one AI session against the whole workspace. An optional `root_repo` URL clones a scaffold repo as the workspace root before child repos are placed inside it; the scaffold provides context files (e.g., CLAUDE.md) but is never branched, committed to, or PR'd. +- **Hosting**: Each workspace declares a `hosting` field (`"github"` or `"gitlab"`, defaults to `"github"`). The hosting router in `services/hosting/` dispatches VCS operations to the correct backend based on this setting. +- **GitLab configuration**: When any workspace uses `hosting: gitlab`, the top-level `gitlab` section must be configured with `base_url`, `access_token`, `bot_username`, and `bot_email`. Auth uses Personal Access Tokens (PAT) or Project/Group Access Tokens. - **Profiles** bundle container, imports, instructions, and workflow settings. Repos within workspaces reference profiles by name. Profile settings override repo-level `.ai-bot/` files when set, enabling prototyping without committing to the source repo. - `Components` maps Jira component names to workspaces (case-insensitive). `DefaultWorkspace` is used when tickets have no matching component. - **Fork mode**: `fork_mode: true` on a project config requires fork-based contributions. Commits are pushed to the assignee's fork (looked up via `jira.assignee_to_github_username`) and PRs are created as cross-repo PRs. When disabled (default), commits go directly to the upstream repo. Missing assignee mappings in fork-mode projects apply the `fork_user_missing` failure label and skip the ticket. @@ -289,6 +292,8 @@ stub := &executortest.StubPipeline{ Environment variables follow the pattern `JIRA_AI_
_`: - `JIRA_AI_JIRA_BASE_URL` -> `jira.base_url` - `JIRA_AI_GITHUB_APP_ID` -> `github.app_id` +- `JIRA_AI_GITLAB_BASE_URL` -> `gitlab.base_url` +- `JIRA_AI_GITLAB_ACCESS_TOKEN` -> `gitlab.access_token` - `JIRA_AI_AI_PROVIDER` -> `ai_provider` - `JIRA_AI_WORKSPACES_BASE_DIR` -> `workspaces.base_dir` - `JIRA_AI_GUARDRAILS_MAX_CONCURRENT_JOBS` -> `guardrails.max_concurrent_jobs` @@ -299,7 +304,8 @@ See `models/config.go` LoadConfig() for complete environment variable binding. - `main.go`: Application entry point, service wiring, HTTP server, graceful shutdown - `models/`: Configuration and data structures (Jira types, domain types) -- `services/`: Infrastructure service implementations (Jira REST API, GitHub App/Git Data API) +- `services/`: Infrastructure service implementations (Jira REST API, GitHub App/Git Data API, GitLab PAT/MR API, shared GitOps) +- `services/hosting/`: Multi-provider routing (dispatches to GitHub or GitLab based on workspace config) - `tracker/`: IssueTracker interface and Jira adapter - `workspace/`: Ticket-scoped workspace management - `container/`: Container runtime detection, image resolution, lifecycle management diff --git a/config.example.yaml b/config.example.yaml index 5d15128..995177b 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -111,6 +111,15 @@ jira: profile: go-dev target_branch: master # older repos may use "master" + # GitLab workspace: set hosting to "gitlab" for repos on GitLab. + # Requires the gitlab section to be configured above. + # gitlab-backend: + # hosting: gitlab + # repos: + # - name: backend + # url: https://gitlab.com/your-org/backend.git + # profile: go-dev + # Multi-repo workspace: all repos cloned into subdirectories # of the workspace and mounted into a single container. # Requires a workspace-level container with all toolchains. @@ -316,6 +325,79 @@ github: # - "license/cla" # - "codecov/patch" +# GitLab Configuration (OPTIONAL — only required when workspaces use hosting: gitlab) +# +# Uses Personal Access Token (PAT) or Project/Group Access Token for +# authentication. Unlike GitHub App auth, GitLab tokens are simpler to +# set up: create a token with the right scopes and paste it here. +# +# Token types (choose one): +# - Personal Access Token: tied to a user account. Simplest for testing. +# Create at: https://YOUR-GITLAB/-/user_settings/personal_access_tokens +# - Project Access Token: tied to a specific project. Survives employee +# offboarding. Create at: Project > Settings > Access Tokens. +# - Group Access Token: covers all projects in a group. Best for multi-repo. +# Create at: Group > Settings > Access Tokens. +# +# Required token scopes: api, read_repository, write_repository +# +# See docs/gitlab-support.md for full deployment guide. +# +# gitlab: +# # Base URL of the GitLab instance (REQUIRED when using GitLab hosting) +# # For gitlab.com: "https://gitlab.com" +# # For self-managed: "https://gitlab.your-company.com" +# base_url: "https://gitlab.com" +# +# # Access token (REQUIRED) +# # The token must have scopes: api, read_repository, write_repository +# # Environment variable: JIRA_AI_GITLAB_ACCESS_TOKEN +# access_token: "glpat-xxxxxxxxxxxxxxxxxxxx" +# +# # Bot identity for git commits (REQUIRED) +# # These appear as the commit author on merge requests. +# # For project tokens, use the token name and a team email. +# # For personal tokens, use your bot account's name and email. +# bot_username: "ai-bot" +# bot_email: "ai-bot@example.com" +# +# # Default label applied to merge requests created by the bot. +# # Useful for filtering bot MRs in GitLab's MR list. +# mr_label: ai-mr +# +# # Optional: Path to SSH private key for commit signing. +# # When set, commits are signed with this key and show as "Verified" +# # in GitLab (requires the public key to be added to the bot account). +# # ssh_key_path: "/path/to/ssh_signing_key" +# +# # GitLab label that tells the bot to skip an MR entirely. +# # When this label is present on an MR, the bot will not process review +# # comments, CI failures, or merge conflicts for that MR. Removing the +# # label re-enables processing on the next scan cycle. +# # Set to empty string to disable the feature. +# skip_mr_label: ai-bot-skip +# +# # Bot loop prevention settings +# # Maximum number of bot replies allowed in a single discussion thread. +# # Prevents infinite loops when two bots reply to each other. +# max_thread_depth: 5 +# +# # Known bot usernames — prevents bot-to-bot conversation loops. +# # Comments from these users are processed initially but loop prevention +# # stops reply chains between bots. +# # NOTE: Do NOT include yourself (bot_username) — that's handled automatically. +# known_bot_usernames: [] +# # - "project_123_bot" +# # - "another-automation" +# +# # Usernames whose MR comments are completely ignored. +# # Use for CI/pipeline bots whose comments are status updates, not code +# # review feedback. Differs from known_bot_usernames: ignored users' +# # comments are completely skipped (never processed), while known bots' +# # comments are processed initially but loop prevention stops chains. +# ignored_usernames: [] +# # - "gitlab-ci-pipeline" + # AI Provider Selection (choose one: "claude" or "gemini") ai_provider: claude diff --git a/docs/gitlab-support.md b/docs/gitlab-support.md new file mode 100644 index 0000000..0f38acf --- /dev/null +++ b/docs/gitlab-support.md @@ -0,0 +1,379 @@ +# GitLab Support + +Jira AI Issue Solver watches Jira tickets, runs AI agents (Claude or Gemini) in ephemeral containers against your codebase, and creates pull requests or merge requests with the results. It handles the full lifecycle: ticket discovery, workspace management, container orchestration, PR/MR creation, and review feedback processing. This guide covers deploying and using the bot with GitLab-hosted repositories. + +## Architecture + +```mermaid +flowchart TD + Jira[Jira Tickets] -->|polls| WIS[WorkItemScanner] + WIS -->|submits job| Coord[Coordinator] + Coord -->|enforces limits| Pipeline[Executor Pipeline] + Pipeline -->|clones repo| WS[Workspace Manager] + Pipeline -->|runs AI| Container[Container Manager] + Pipeline -->|creates MR/PR| Router[Hosting Router] + Router -->|"hosting: github"| GH[GitHubService] + Router -->|"hosting: gitlab"| GL[GitLabService] + GL -->|PAT auth| GitLab[GitLab Instance] + GH -->|App auth| GitHub[GitHub] + + FS[FeedbackScanner] -->|review comments| Coord + MS[MergeScanner] -->|branch updates| Coord +``` + +### Key Packages + +| Package | Role | +|---------|------| +| `scanner/` | Polls Jira for new tickets and monitors PRs/MRs for review comments | +| `jobmanager/` | Enforces concurrency limits, retries, circuit breaker, and cost budget | +| `executor/` | Orchestrates the full pipeline: clone, branch, AI session, commit, create MR | +| `workspace/` | Manages per-ticket workspace directories (clone, TTL, cleanup) | +| `container/` | Detects runtime (podman/docker), resolves images, runs AI sessions | +| `services/` | Jira REST API, GitHub App API, GitLab PAT API, shared git commands | +| `services/hosting/` | Routes VCS operations to the correct backend per workspace | +| `models/` | Configuration loading, validation, and domain types | +| `recovery/` | Startup crash recovery (orphan cleanup, stuck ticket reset) | + +### How the Hosting Router Works + +Each workspace in the project config declares a `hosting` field (`"github"` or `"gitlab"`). At startup, `main.go` builds a map of `owner/repo` to provider. The hosting router satisfies all consumer interfaces and dispatches each method call to the correct backend: + +- **API-based calls** (e.g., `CreatePR`, `GetPRComments`) are routed by owner/repo. +- **Directory-based calls** (e.g., `CreateBranch`, `HasChanges`) are routed via a workspace registry populated during `CloneRepository`. +- **Fallback**: repos not explicitly mapped go to the default provider (GitHub if configured, otherwise GitLab). + +## GitLab Configuration + +### 1. Create a GitLab Access Token + +Create a Personal Access Token (PAT) or a Project/Group Access Token on your GitLab instance: + +1. Go to **Settings > Access Tokens** (user-level or project-level) +2. Set a descriptive name (e.g., `jira-ai-bot`) +3. Select scopes: `api`, `read_repository`, `write_repository` +4. Copy the token (starts with `glpat-`) + +For self-managed GitLab instances, project/group access tokens are preferred over personal tokens because they survive employee offboarding. + +### 2. Configure the `gitlab:` Block + +Add to your `config.yaml`: + +```yaml +gitlab: + base_url: "https://gitlab.example.com" # Your GitLab instance URL + access_token: "glpat-xxxxxxxxxxxxxxxxxxxx" # PAT or project token + bot_username: "ai-bot" # Git commit author name + bot_email: "ai-bot@example.com" # Git commit author email + mr_label: "ai-mr" # Label applied to bot MRs + skip_mr_label: "ai-bot-skip" # Label to skip processing an MR + max_thread_depth: 5 # Max bot replies per thread + # ssh_key_path: "/path/to/key" # Optional: SSH signing + # known_bot_usernames: ["project_bot"] # Prevent bot-to-bot loops + # ignored_usernames: [] # Comments to completely skip +``` + +### 3. Set Workspace Hosting to GitLab + +In your project configuration under `jira.projects[].workspaces`, set `hosting: gitlab`: + +```yaml +jira: + projects: + - project_keys: ["MYPROJECT"] + status_transitions: + Bug: + todo: "To Do" + in_progress: "In Progress" + in_review: "In Review" + workspaces: + backend: + hosting: gitlab # <-- routes to GitLab + repos: + - name: backend + url: https://gitlab.example.com/org/backend.git + profile: default + profiles: + default: + container: + image: "registry.example.com/team/dev-image:latest" +``` + +### 4. Environment Variables + +All GitLab config fields can be set via environment variables: + +| Variable | Config equivalent | +|----------|-------------------| +| `JIRA_AI_GITLAB_BASE_URL` | `gitlab.base_url` | +| `JIRA_AI_GITLAB_ACCESS_TOKEN` | `gitlab.access_token` | +| `JIRA_AI_GITLAB_BOT_USERNAME` | `gitlab.bot_username` | +| `JIRA_AI_GITLAB_BOT_EMAIL` | `gitlab.bot_email` | +| `JIRA_AI_GITLAB_MR_LABEL` | `gitlab.mr_label` | +| `JIRA_AI_GITLAB_SSH_KEY_PATH` | `gitlab.ssh_key_path` | +| `JIRA_AI_GITLAB_SKIP_MR_LABEL` | `gitlab.skip_mr_label` | +| `JIRA_AI_GITLAB_MAX_THREAD_DEPTH` | `gitlab.max_thread_depth` | + +## Deployment Guide + +### Prerequisites + +- **Jira**: API token with read/write access to your project(s) +- **GitLab**: Personal Access Token with `api` + `write_repository` scopes +- **AI Provider**: Claude API key (or Vertex AI credentials) or Gemini API key +- **Container Runtime**: podman or docker (for running AI sessions) +- **AI Dev Container Image**: a container image with your project's toolchain (compilers, linters, dependencies) + +### Step 1: Create Configuration + +```bash +cp config.example.yaml config.yaml +``` + +Edit `config.yaml`: +- Fill in `jira.*` credentials +- Fill in `gitlab.*` credentials +- Set `ai_provider` and the corresponding API key +- Configure at least one project with `hosting: gitlab` workspaces +- Set `workspaces.base_dir` to a writable directory + +### Step 2: Build and Run + +**Option A: Run directly** + +```bash +go build -o jira-ai-issue-solver main.go +./jira-ai-issue-solver -config config.yaml +``` + +**Option B: Container deployment** + +```bash +make build +make run +``` + +**Option C: Podman Compose** + +```bash +podman-compose -f podman-compose.yml up -d +``` + +### Step 3: Verify + +```bash +curl http://localhost:8080/health +# Should return: OK +``` + +Check the logs for successful scanner startup: + +``` +INFO Starting work item scanner +INFO Starting feedback scanner +INFO Starting merge scanner +``` + +### Step 4: Create a Test Ticket + +1. Create a Jira ticket in your configured project +2. Set the ticket type to one with configured status transitions (e.g., Bug) +3. Set the status to the configured `todo` value (e.g., "To Do") +4. Assign a component that maps to your GitLab workspace (or use `default_workspace`) + +The bot will: +1. Pick up the ticket within one poll cycle (default: 5 minutes) +2. Transition it to "In Progress" +3. Clone the repo, run the AI agent in a container +4. Push a branch and create a merge request on GitLab +5. Transition the ticket to "In Review" and post the MR link + +## User Workflow + +### Day-to-Day Usage + +```mermaid +sequenceDiagram + participant Dev as Developer + participant Jira as Jira + participant Bot as AI Bot + participant GL as GitLab + + Dev->>Jira: Create ticket (Bug/Task/Story) + Dev->>Jira: Set status to "To Do" + Bot->>Jira: Picks up ticket (polling) + Bot->>Jira: Transitions to "In Progress" + Bot->>GL: Clones repo, creates branch + Bot->>Bot: Runs AI in container + Bot->>GL: Pushes commits, creates MR + Bot->>Jira: Transitions to "In Review", posts MR link + Dev->>GL: Reviews MR, leaves comments + Bot->>GL: Detects comments, responds with fixes + Dev->>GL: Approves and merges MR + Bot->>Jira: Transitions to "Merged" (if configured) +``` + +### Interacting with the Bot + +**The bot responds to MR review comments automatically.** Leave comments on specific lines or as general notes on the MR, and the bot will: +1. Detect the unaddressed comment on its next poll cycle +2. Run another AI session with the review context +3. Push new commits addressing the feedback +4. Reply to the comment thread + +**Skipping a merge request:** Add the `ai-bot-skip` label (configurable via `gitlab.skip_mr_label`) to any MR to prevent the bot from processing it. + +**Re-triggering after rejection:** If a reviewer closes the MR without merging, the bot applies the `rejected` failure label (if configured). Reopen or recreate the ticket to retry. + +### Jira Commands (via ticket status) + +The bot is driven by Jira ticket status, not comments: + +| Action | How | +|--------|-----| +| Start processing | Set ticket status to the configured `todo` value | +| Stop processing | Transition ticket away from `todo`/`in_progress` | +| Retry after failure | Reset ticket status back to `todo` | + +## Mixed GitHub + GitLab Deployment + +A single bot instance can serve both GitHub and GitLab repositories simultaneously. Each workspace declares its hosting provider independently: + +```yaml +workspaces: + github-frontend: + # hosting defaults to "github" when omitted + repos: + - name: frontend + url: https://github.com/org/frontend.git + profile: node-dev + + gitlab-backend: + hosting: gitlab + repos: + - name: backend + url: https://gitlab.example.com/org/backend.git + profile: go-dev +``` + +The hosting router dispatches operations to the correct provider based on repository ownership. Both the `github:` and `gitlab:` config sections must be present when both providers are in use. + +## Differences from GitHub Mode + +| Aspect | GitHub | GitLab | +|--------|--------|--------| +| Authentication | GitHub App (JWT + installation tokens) | Personal/Project Access Token | +| Commit strategy | Git Data API (create blob, tree, commit, update ref) | Local `git commit` + `git push` | +| PR/MR creation | `POST /repos/:owner/:repo/pulls` | `POST /projects/:id/merge_requests` | +| Review comments | PR review comments API (file-level threading) | MR discussion notes (position-based) | +| CI status | Check Runs API | Pipeline + Jobs API | +| Fork support | Full (cross-repo PRs via `source_project_id`) | Limited (same-project branches) | +| Label events | Timeline events API (tracks label add/remove) | Not available (label removal time unknown) | +| Merge status | Computed async, polled with retries | `has_conflicts` + `merge_status` fields | +| Bot identity | App name + `[bot]` suffix | PAT owner or project token name | + +### Commit Strategy Differences + +**GitHub** uses the Git Data API to create "verified" commits server-side without ever running `git push`. This produces commits attributed to the GitHub App with a "Verified" badge. + +**GitLab** commits locally and pushes with the PAT embedded in the remote URL. Commits are attributed to the token owner. SSH signing (optional) provides commit verification. + +### What This Means in Practice + +- GitLab MRs work identically to GitHub PRs from the user's perspective +- The bot creates branches, commits code, opens MRs, and responds to review comments +- The main difference is the authentication model: one PAT vs a GitHub App installation per org +- GitLab's simpler auth model means faster setup (no App registration, no webhook configuration) + +## Contributing Upstream + +This section documents the strategy for contributing GitLab support back to the upstream `flightctl/jira-ai-issue-solver` repository. + +### PR Split Strategy + +The changeset is split into two PRs for easier review: + +**PR 1: Extract shared GitOps (pure refactor)** + +Files: +- `services/gitops.go` — provider-agnostic git operations extracted from `GitHubServiceImpl` +- `services/gitops_test.go` — tests for shared operations +- `services/github.go` — methods now delegate to `GitOps` (thin wrappers) + +This PR has **zero behavior change**. All existing tests pass without modification. It prepares the codebase for multi-provider support by extracting operations that both GitHub and GitLab share: `CreateBranch`, `SwitchBranch`, `HasChanges`, `StripRemoteAuth`, `FetchRemote`, `SyncWithRemote`, `MergeBase`, `CloneImport`, `StageAndCommitLocal`. + +**PR 2: Add GitLab hosting support (builds on PR 1)** + +Files: +- `services/gitlab.go` + `services/gitlab_test.go` — GitLab service implementation +- `services/hosting/router.go` + `services/hosting/router_test.go` — multi-provider router +- `models/config.go` — `GitLab` config struct, workspace `Hosting` field, conditional validation +- `main.go` — conditional service creation, router wiring +- `config.example.yaml` — GitLab configuration section +- `AGENTS.md` — documentation updates +- `docs/gitlab-support.md` — this guide + +### PR Description Template + +```markdown +## Summary + +Add per-project GitLab hosting alongside existing GitHub support. Each workspace +declares its hosting provider (`github` or `gitlab`), and a hosting router +dispatches VCS operations to the correct backend. + +## Design + +- **Hosting router** (`services/hosting/router.go`): satisfies all consumer + interfaces, dispatches by owner/repo for API calls and by workspace directory + for local git operations. Falls back to the default provider for unmapped repos. +- **GitLab service** (`services/gitlab.go`): uses PAT auth and the GitLab REST + API v4. Commits via local `git push` (vs GitHub's Git Data API). No external + dependencies beyond stdlib `net/http`. +- **Shared GitOps** (`services/gitops.go`): provider-agnostic git commands + extracted from GitHubServiceImpl. Both providers embed this struct. +- **Conditional validation**: GitHub credentials are only required when + workspaces use `hosting: github`; same for GitLab. + +## Backward Compatibility + +- Zero changes to existing GitHub-only deployments +- GitHub validation is only enforced when GitHub hosting is in use +- Default hosting is `github` (no config change needed for existing users) +- All existing tests pass without modification + +## Test Coverage + +- `services/gitlab_test.go`: HTTP mock tests for MR creation, comments, labels, CI +- `services/hosting/router_test.go`: dispatch logic, fallback, workspace registry +- `services/gitops_test.go`: shared git operations (real git commands on temp repos) + +## Configuration + +Workspace-level `hosting` field: + +```yaml +workspaces: + my-gitlab-project: + hosting: gitlab + repos: + - name: backend + url: https://gitlab.example.com/org/backend.git + profile: default +``` +``` + +### What to Include + +- Motivation: teams using GitLab can now adopt the bot without a mirror/sync layer +- The architectural fit: consumer-defined interfaces already isolate VCS concerns +- No new external dependencies (pure stdlib HTTP client, no go-gitlab SDK) +- Test results: `go test ./...` passes + +### What NOT to Include + +- Deployment-specific details (container images, internal GitLab URLs, team names) +- References to specific internal projects or Jira boards +- Fork/licensing history (resolved privately before the PR) +- Future plans (triage, pushback, webhooks) — these are separate features diff --git a/main.go b/main.go index 61a794a..1a08a7d 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "os/signal" "path/filepath" "strconv" + "strings" "syscall" "time" @@ -24,6 +25,7 @@ import ( "jira-ai-issue-solver/recovery" "jira-ai-issue-solver/scanner" "jira-ai-issue-solver/services" + "jira-ai-issue-solver/services/hosting" "jira-ai-issue-solver/taskfile" "jira-ai-issue-solver/tracker/jira" "jira-ai-issue-solver/workspace" @@ -45,7 +47,28 @@ func main() { // --- Infrastructure --- jiraService := services.NewJiraService(config, logger) - gitService := services.NewGitHubService(config, logger) + + // Build the VCS hosting router from per-project workspace config. + needsGitHub, needsGitLab := config.RequiredHostingProviders() + + var ghService *services.GitHubServiceImpl + if needsGitHub { + ghService = services.NewGitHubService(config, logger) + } + + var glService *services.GitLabServiceImpl + if needsGitLab { + glService = services.NewGitLabService(config, logger) + } + + repoProviders := buildRepoProviderMap(config, ghService, glService) + var fallback hosting.Provider + if ghService != nil { + fallback = ghService + } else { + fallback = glService + } + gitService := hosting.NewRouter(repoProviders, fallback) issueTracker, err := jira.NewAdapter(jiraService, logger) if err != nil { @@ -478,3 +501,46 @@ func appendUnique(slice []string, value string) []string { } return append(slice, value) } + +// buildRepoProviderMap iterates all configured projects/workspaces and +// maps each repo URL's owner/repo to the correct hosting provider. +func buildRepoProviderMap( + config *models.Config, + ghService *services.GitHubServiceImpl, + glService *services.GitLabServiceImpl, +) map[string]hosting.Provider { + providers := make(map[string]hosting.Provider) + + for _, project := range config.Jira.Projects { + for _, ws := range project.Workspaces { + var provider hosting.Provider + switch ws.HostingProvider() { + case models.HostingGitLab: + provider = glService + default: + provider = ghService + } + for _, repo := range ws.Repos { + owner, repoName := extractOwnerRepoFromURL(repo.URL) + if owner != "" && repoName != "" { + key := owner + "/" + repoName + providers[key] = provider + } + } + } + } + + return providers +} + +// extractOwnerRepoFromURL parses owner and repo from a clone URL. +func extractOwnerRepoFromURL(repoURL string) (string, string) { + repoURL = strings.TrimSuffix(repoURL, ".git") + parts := strings.Split(repoURL, "/") + if len(parts) >= 5 { + repo := parts[len(parts)-1] + owner := strings.Join(parts[3:len(parts)-1], "/") + return owner, repo + } + return "", "" +} diff --git a/models/config.go b/models/config.go index 7a6376d..8c44cb8 100644 --- a/models/config.go +++ b/models/config.go @@ -110,6 +110,11 @@ type Profile struct { // repositories that constitute a working environment for AI sessions. // Single-repo projects are just workspaces with one entry. type WorkspaceConfig struct { + // Hosting selects the code hosting provider for this workspace. + // Valid values: "github" (default), "gitlab". All repos in the + // workspace must reside on the same hosting provider. + Hosting string `yaml:"hosting" mapstructure:"hosting"` + // Container holds workspace-level container settings. Required for // multi-repo workspaces (the "fat container" with all toolchains). // For single-repo workspaces, this may be empty — the repo's @@ -514,6 +519,22 @@ type Config struct { SkipPRLabel string `yaml:"skip_pr_label" mapstructure:"skip_pr_label" default:"ai-bot-skip"` // GitHub label that tells the bot to skip a PR } `yaml:"github" mapstructure:"github"` + // GitLab configuration (optional — required only when workspaces + // use hosting: gitlab). Uses Personal Access Token or Project + // Access Token for authentication. + GitLab struct { + BaseURL string `yaml:"base_url" mapstructure:"base_url"` // e.g., "https://gitlab.com" or "https://gitlab.cee.redhat.com" + AccessToken string `yaml:"access_token" mapstructure:"access_token"` // PAT or project/group access token + BotUsername string `yaml:"bot_username" mapstructure:"bot_username"` // Git commit author name + BotEmail string `yaml:"bot_email" mapstructure:"bot_email"` // Git commit author email + MRLabel string `yaml:"mr_label" mapstructure:"mr_label"` // Default label applied to merge requests + SSHKeyPath string `yaml:"ssh_key_path" mapstructure:"ssh_key_path"` // Optional: SSH key for commit signing + SkipMRLabel string `yaml:"skip_mr_label" mapstructure:"skip_mr_label"` // GitLab label that tells the bot to skip an MR + MaxThreadDepth int `yaml:"max_thread_depth" mapstructure:"max_thread_depth"` + KnownBotUsernames []string `yaml:"known_bot_usernames" mapstructure:"known_bot_usernames"` + IgnoredUsernames []string `yaml:"ignored_usernames" mapstructure:"ignored_usernames"` + } `yaml:"gitlab" mapstructure:"gitlab"` + // AI Provider selection AIProvider string `yaml:"ai_provider" mapstructure:"ai_provider" default:"claude"` // "claude" or "gemini" @@ -782,6 +803,45 @@ func (c *Config) GetBotEmail() string { return "" } +// HostingProvider constants. +const ( + HostingGitHub = "github" + HostingGitLab = "gitlab" +) + +// HostingProvider returns the normalized hosting provider for the workspace. +// Defaults to "github" when the field is empty. +func (w *WorkspaceConfig) HostingProvider() string { + switch strings.ToLower(w.Hosting) { + case HostingGitLab: + return HostingGitLab + default: + return HostingGitHub + } +} + +// RequiredHostingProviders scans all project workspaces and returns which +// hosting providers are in use. GitHub is always needed if any workspace +// uses it (or has no explicit hosting field, since github is the default). +func (c *Config) RequiredHostingProviders() (needsGitHub, needsGitLab bool) { + for _, project := range c.Jira.Projects { + for _, ws := range project.Workspaces { + switch ws.HostingProvider() { + case HostingGitLab: + needsGitLab = true + default: + needsGitHub = true + } + } + } + // If no workspaces are configured at all, default to needing GitHub + // (backward compatibility). + if !needsGitHub && !needsGitLab { + needsGitHub = true + } + return +} + // LoadConfig loads configuration from multiple sources with Viper // Priority order: Environment variables > Config file > .env file > Defaults func LoadConfig(configPath string) (*Config, error) { @@ -835,6 +895,18 @@ func LoadConfig(configPath string) (*Config, error) { bindEnv("github.ignored_check_names") bindEnv("github.skip_pr_label") + // GitLab configuration + bindEnv("gitlab.base_url") + bindEnv("gitlab.access_token") + bindEnv("gitlab.bot_username") + bindEnv("gitlab.bot_email") + bindEnv("gitlab.mr_label") + bindEnv("gitlab.ssh_key_path") + bindEnv("gitlab.skip_mr_label") + bindEnv("gitlab.max_thread_depth") + bindEnv("gitlab.known_bot_usernames") + bindEnv("gitlab.ignored_usernames") + // AI configuration bindEnv("ai_provider") @@ -1089,6 +1161,11 @@ func setDefaults(v *viper.Viper) { "codeclimate", }) + // GitLab defaults + v.SetDefault("gitlab.mr_label", "ai-mr") + v.SetDefault("gitlab.skip_mr_label", "ai-bot-skip") + v.SetDefault("gitlab.max_thread_depth", 5) + // AI Provider defaults v.SetDefault("ai_provider", "claude") @@ -1163,43 +1240,61 @@ func (c *Config) validate() error { } } - // GitHub validation - App credentials required - if c.GitHub.AppID <= 0 { - return errors.New("github.app_id must be a positive integer") - } - if c.GitHub.PrivateKeyPath == "" { - return errors.New("github.private_key_path must be provided") - } - if _, err := os.Stat(c.GitHub.PrivateKeyPath); os.IsNotExist(err) { - return fmt.Errorf("github.private_key_path file does not exist: %s", c.GitHub.PrivateKeyPath) - } + // Determine which hosting providers are in use. + needsGitHub, needsGitLab := c.RequiredHostingProviders() - if c.GitHub.BotUsername == "" { - return errors.New("github.bot_username is required") - } + // GitHub validation — required when any workspace uses github hosting. + if needsGitHub { + if c.GitHub.AppID <= 0 { + return errors.New("github.app_id must be a positive integer") + } + if c.GitHub.PrivateKeyPath == "" { + return errors.New("github.private_key_path must be provided") + } + if _, err := os.Stat(c.GitHub.PrivateKeyPath); os.IsNotExist(err) { + return fmt.Errorf("github.private_key_path file does not exist: %s", c.GitHub.PrivateKeyPath) + } - // Validate bot email can be determined - if c.GetBotEmail() == "" { - return errors.New("github.bot_email is required (either set explicitly, or it will be auto-constructed from app_id)") - } + if c.GitHub.BotUsername == "" { + return errors.New("github.bot_username is required") + } - // Validate bot username doesn't contain characters that could cause issues - invalidChars := []string{"/", "\\", ":", "*", "?", "\"", "<", ">", "|", "\n", "\r", "\t"} - for _, char := range invalidChars { - if strings.Contains(c.GitHub.BotUsername, char) { - return fmt.Errorf("github.bot_username contains invalid character %q - bot username will be used in branch names and must be git-safe", char) + if c.GetBotEmail() == "" { + return errors.New("github.bot_email is required (either set explicitly, or it will be auto-constructed from app_id)") } - } - // Validate known bot usernames don't contain problematic characters - for _, botUsername := range c.GitHub.KnownBotUsernames { + invalidChars := []string{"/", "\\", ":", "*", "?", "\"", "<", ">", "|", "\n", "\r", "\t"} for _, char := range invalidChars { - if strings.Contains(botUsername, char) { - return fmt.Errorf("github.known_bot_usernames contains username %q with invalid character %q", botUsername, char) + if strings.Contains(c.GitHub.BotUsername, char) { + return fmt.Errorf("github.bot_username contains invalid character %q - bot username will be used in branch names and must be git-safe", char) + } + } + + for _, botUsername := range c.GitHub.KnownBotUsernames { + for _, char := range invalidChars { + if strings.Contains(botUsername, char) { + return fmt.Errorf("github.known_bot_usernames contains username %q with invalid character %q", botUsername, char) + } } } } + // GitLab validation — required when any workspace uses gitlab hosting. + if needsGitLab { + if c.GitLab.BaseURL == "" { + return errors.New("gitlab.base_url is required when any workspace uses hosting: gitlab") + } + if c.GitLab.AccessToken == "" { + return errors.New("gitlab.access_token is required when any workspace uses hosting: gitlab") + } + if c.GitLab.BotUsername == "" { + return errors.New("gitlab.bot_username is required when any workspace uses hosting: gitlab") + } + if c.GitLab.BotEmail == "" { + return errors.New("gitlab.bot_email is required when any workspace uses hosting: gitlab") + } + } + // Validate workspaces configuration if c.Workspaces.BaseDir == "" { return errors.New("workspaces.base_dir is required") @@ -1257,6 +1352,9 @@ func (p *ProjectConfig) validate(index int) error { // Validate each workspace. for wsName, ws := range p.Workspaces { + if h := strings.ToLower(ws.Hosting); h != "" && h != HostingGitHub && h != HostingGitLab { + return fmt.Errorf("%s.workspaces.%s.hosting: invalid value %q (must be %q or %q)", prefix, wsName, ws.Hosting, HostingGitHub, HostingGitLab) + } if len(ws.Repos) == 0 { return fmt.Errorf("%s.workspaces.%s: at least one repo is required", prefix, wsName) } diff --git a/services/github.go b/services/github.go index d94ba29..693e908 100644 --- a/services/github.go +++ b/services/github.go @@ -9,7 +9,6 @@ import ( "fmt" "io" "net/http" - "net/url" "os" "os/exec" "path/filepath" @@ -94,6 +93,7 @@ type GitHubServiceImpl struct { executor models.CommandExecutor mergeRetryDelay time.Duration logger *zap.Logger + gitOps *GitOps } // gitCommand encapsulates a git command execution with optional stdout/stderr capture. @@ -182,6 +182,7 @@ func NewGitHubService(config *models.Config, logger *zap.Logger, executor ...mod executor: commandExecutor, mergeRetryDelay: mergeabilityRetryDelay, logger: logger, + gitOps: NewGitOps(commandExecutor, logger), } // Initialize GitHub App transport @@ -441,67 +442,7 @@ func (s *GitHubServiceImpl) getAuthTokenForRepo(owner, repo string) (string, err // CreateBranch creates a new branch in a local repository based on the latest target branch func (s *GitHubServiceImpl) CreateBranch(directory, branchName, baseBranch string) error { - debugEnabled := s.logger.Core().Enabled(zapcore.DebugLevel) - fn := zap.String("function", "CreateBranch") - - // Reset any dirty state left by a previous failed attempt. - resetCmd := newGitCommand(s.executor("git", "reset", "--hard", "HEAD"), directory, debugEnabled, true) - if err := resetCmd.run(); err != nil { - s.logger.Warn("git reset --hard HEAD failed (non-fatal)", - fn, zap.Error(err), zap.String("stderr", resetCmd.getStderr())) - } - - // Fetch the latest changes from origin - cmd := newGitCommand(s.executor("git", "fetch", "origin"), directory, debugEnabled, true) - - if err := cmd.run(); err != nil { - return fmt.Errorf("failed to fetch origin: %w, stderr: %s", err, cmd.getStderr()) - } - - s.logger.Debug("git fetch origin", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) - - // Checkout the target branch - cmd = newGitCommand(s.executor("git", "checkout", baseBranch), directory, debugEnabled, true) - - if err := cmd.run(); err != nil { - return fmt.Errorf("failed to checkout target branch %s: %w, stderr: %s", baseBranch, err, cmd.getStderr()) - } - - s.logger.Debug("git checkout", fn, zap.String("branch", baseBranch), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) - - // Reset to the latest commit on the target branch to ensure we're up to date - cmd = newGitCommand(s.executor("git", "reset", "--hard", "origin/"+baseBranch), directory, debugEnabled, true) - - if err := cmd.run(); err != nil { - return fmt.Errorf("failed to reset to latest commit on target branch %s: %w, stderr: %s", baseBranch, err, cmd.getStderr()) - } - s.logger.Debug("git reset --hard", fn, zap.String("ref", "origin/"+baseBranch), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) - - // Check if the branch already exists locally - cmd = newGitCommand(s.executor("git", "show-ref", "--verify", "--quiet", "refs/heads/"+branchName), directory, debugEnabled, true) - - if err := cmd.run(); err == nil { - // Branch exists locally, delete it first - s.logger.Info("Branch already exists locally, deleting it", zap.String("branchName", branchName)) - cmd = newGitCommand(s.executor("git", "branch", "-D", branchName), directory, debugEnabled, true) - - if err := cmd.run(); err != nil { - return fmt.Errorf("failed to delete existing branch %s: %w, stderr: %s", branchName, err, cmd.getStderr()) - } - - s.logger.Debug("git branch -D", fn, zap.String("branch", branchName), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) - } - - // Create a new branch from the current state - cmd = newGitCommand(s.executor("git", "checkout", "-b", branchName), directory, debugEnabled, true) - - if err := cmd.run(); err != nil { - return fmt.Errorf("failed to create branch: %w, stderr: %s", err, cmd.getStderr()) - } - - s.logger.Debug("git checkout", fn, zap.String("operation", "-b"), zap.String("branch", branchName), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) - - return nil + return s.gitOps.CreateBranch(directory, branchName, baseBranch) } // CommitChanges creates a verified commit via the GitHub API from local @@ -1584,188 +1525,24 @@ func (s *GitHubServiceImpl) CreatePR(params models.PRParams) (*models.PR, error) // SwitchBranch switches to a specific branch. func (s *GitHubServiceImpl) SwitchBranch(directory, branchName string) error { - debugEnabled := s.logger.Core().Enabled(zapcore.DebugLevel) - fn := zap.String("function", "SwitchBranch") - - // Reset any dirty state left by a previous failed attempt (e.g., - // unresolved merge conflicts). Without this, git checkout fails - // with "you need to resolve your current index first." - resetCmd := newGitCommand(s.executor("git", "reset", "--hard", "HEAD"), directory, debugEnabled, true) - if err := resetCmd.run(); err != nil { - s.logger.Warn("git reset --hard HEAD failed (non-fatal)", - fn, zap.Error(err), zap.String("stderr", resetCmd.getStderr())) - } - - // Fetch the latest changes from origin - cmd := newGitCommand(s.executor("git", "fetch", "origin"), directory, debugEnabled, true) - - if err := cmd.run(); err != nil { - return fmt.Errorf("failed to fetch origin: %w, stderr: %s", err, cmd.getStderr()) - } - s.logger.Debug("git fetch origin", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) - - // Checkout the specified branch - cmd = newGitCommand(s.executor("git", "checkout", branchName), directory, debugEnabled, true) - - if err := cmd.run(); err != nil { - return fmt.Errorf("failed to checkout branch %s: %w, stderr: %s", branchName, err, cmd.getStderr()) - } - - s.logger.Debug("git checkout", fn, zap.String("branch", branchName), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) - - return nil + return s.gitOps.SwitchBranch(directory, branchName) } -// HasChanges checks if there are any uncommitted changes in the repository -// Returns true if there are changes (modified, added, or deleted files) func (s *GitHubServiceImpl) HasChanges(directory, baseBranch string) (bool, error) { - fn := zap.String("function", "HasChanges") - - // Check for working tree changes - hasWorkingTreeChanges, err := s.hasWorkingTreeChanges(directory, fn) - if err != nil { - return false, err - } - if hasWorkingTreeChanges { - return true, nil - } - - // Check for unpushed commits (e.g., merge commits created by AI) - hasUnpushedCommits, err := s.hasUnpushedCommits(directory, baseBranch, fn) - if err != nil { - return false, err - } - - return hasUnpushedCommits, nil + return s.gitOps.HasChanges(directory, baseBranch) } -// hasWorkingTreeChanges checks if there are uncommitted changes in the working tree -func (s *GitHubServiceImpl) hasWorkingTreeChanges(directory string, fn zapcore.Field) (bool, error) { - // Use git status --porcelain to get machine-readable status - // Empty output means no changes - // Always capture stdout since we need to check if there's output - cmd := newGitCommand(s.executor("git", "status", "--porcelain"), directory, true, true) - - if err := cmd.run(); err != nil { - return false, fmt.Errorf("failed to check git status: %w, stderr: %s", err, cmd.getStderr()) - } - - s.logger.Debug("git status --porcelain", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) - - // If stdout is empty, there are no working tree changes - return cmd.hasStdout(), nil -} -// stageAndCommitLocal ensures all working tree and staged changes are -// committed locally. This normalizes the three possible states an AI -// session can leave behind (committed, staged, or unstaged) into a -// single committed state that git diff-tree can see. func (s *GitHubServiceImpl) stageAndCommitLocal(directory string, fn zapcore.Field) error { - // Check for uncommitted changes (staged or unstaged). - statusCmd := newGitCommand(s.executor("git", "status", "--porcelain"), directory, true, true) - if err := statusCmd.run(); err != nil { - return fmt.Errorf("git status: %w, stderr: %s", err, statusCmd.getStderr()) - } - if !statusCmd.hasStdout() { - // Everything is already committed. - return nil - } - - s.logger.Debug("Staging uncommitted changes", fn) - - addCmd := newGitCommand(s.executor("git", "add", "-A"), directory, false, true) - if err := addCmd.run(); err != nil { - return fmt.Errorf("git add -A: %w, stderr: %s", err, addCmd.getStderr()) - } - - commitCmd := newGitCommand( - s.executor("git", "commit", "-m", "AI changes (local only)"), - directory, false, true) - if err := commitCmd.run(); err != nil { - return fmt.Errorf("git commit: %w, stderr: %s", err, commitCmd.getStderr()) - } - - s.logger.Debug("Committed local changes", fn) - return nil + return s.gitOps.StageAndCommitLocal(directory, fn) } -// hasUnpushedCommits checks if there are local commits that haven't been pushed to origin -func (s *GitHubServiceImpl) hasUnpushedCommits(directory, baseBranch string, fn zapcore.Field) (bool, error) { - // First, check if origin remote exists - remoteCmd := newGitCommand(s.executor("git", "remote", "get-url", "origin"), directory, false, false) - if err := remoteCmd.run(); err != nil { - // No origin remote configured - this is fine, means no unpushed commits to check - s.logger.Debug("No origin remote configured", fn) - return false, nil - } - - // Get the current branch name - // Always capture stdout since we need the output - branchCmd := newGitCommand(s.executor("git", "rev-parse", "--abbrev-ref", "HEAD"), directory, true, true) - if err := branchCmd.run(); err != nil { - return false, fmt.Errorf("failed to get current branch: %w, stderr: %s", err, branchCmd.getStderr()) - } - - branchName := strings.TrimSpace(branchCmd.getStdout()) - if branchName == "" { - return false, fmt.Errorf("unable to determine current branch") - } - - s.logger.Debug("Current branch", fn, zap.String("branch", branchName)) - - // Determine the remote ref to compare against: origin/ if it - // exists, otherwise origin/ (the branch we forked from). - remoteRef := fmt.Sprintf("origin/%s", branchName) - remoteExistsCmd := newGitCommand(s.executor("git", "rev-parse", "--verify", remoteRef), directory, false, false) - if err := remoteExistsCmd.run(); err != nil { - // Remote branch doesn't exist. Compare against origin/ - // to check if HEAD has diverged (i.e., the AI made local commits). - remoteRef = fmt.Sprintf("origin/%s", baseBranch) - s.logger.Debug("Remote branch does not exist, comparing against target branch", fn, - zap.String("branch", branchName), - zap.String("targetRef", remoteRef)) - } - - // Check for commits that exist locally but not on the remote ref. - logCmd := newGitCommand(s.executor("git", "log", fmt.Sprintf("%s..HEAD", remoteRef), "--oneline"), directory, true, true) - if err := logCmd.run(); err != nil { - return false, fmt.Errorf("failed to check unpushed commits: %w, stderr: %s", err, logCmd.getStderr()) - } - - s.logger.Debug("git log ref..HEAD", fn, - zap.String("ref", remoteRef), - zap.String("stdout", logCmd.getStdout()), - zap.String("stderr", logCmd.getStderr())) - - // If there's any output, we have unpushed commits - return logCmd.hasStdout(), nil -} // StripRemoteAuth removes authentication credentials from the // workspace's origin remote URL. After this call, push operations // will be rejected by the remote. func (s *GitHubServiceImpl) StripRemoteAuth(directory string) error { - cmd := newGitCommand(s.executor("git", "remote", "get-url", "origin"), directory, false, true) - if err := cmd.run(); err != nil { - return fmt.Errorf("get remote URL: %w, stderr: %s", err, cmd.getStderr()) - } - - rawURL := strings.TrimSpace(cmd.getStdout()) - parsed, err := url.Parse(rawURL) - if err != nil { - return fmt.Errorf("parse remote URL: %w", err) - } - parsed.User = nil - - setCmd := newGitCommand( - s.executor("git", "remote", "set-url", "origin", parsed.String()), - directory, false, false) - if err := setCmd.run(); err != nil { - return fmt.Errorf("strip remote auth: %w, stderr: %s", err, setCmd.getStderr()) - } - - s.logger.Debug("Stripped remote auth", zap.String("directory", directory)) - return nil + return s.gitOps.StripRemoteAuth(directory) } // RestoreRemoteAuth restores authentication credentials on the @@ -1788,91 +1565,14 @@ func (s *GitHubServiceImpl) RestoreRemoteAuth(directory, owner, repo string) err return nil } -// SyncWithRemote reconciles the local workspace with the remote branch by -// fetching and hard-resetting to the remote ref. Excluded artifact -// directories are preserved across the reset because they are filtered -// from API commits and therefore absent on the remote branch. -// FetchRemote fetches all refs from the origin remote. Used in -// fork-based workflows to make fork branches available in a -// workspace that was originally cloned from upstream. func (s *GitHubServiceImpl) FetchRemote(directory string) error { - debugEnabled := s.logger.Core().Enabled(zapcore.DebugLevel) - fn := zap.String("function", "FetchRemote") - - fetchCmd := newGitCommand(s.executor("git", "fetch", "origin"), directory, debugEnabled, true) - if err := fetchCmd.run(); err != nil { - return fmt.Errorf("failed to fetch from origin: %w, stderr: %s", err, fetchCmd.getStderr()) - } - s.logger.Debug("git fetch origin", fn, zap.String("stdout", fetchCmd.getStdout()), zap.String("stderr", fetchCmd.getStderr())) - - return nil + return s.gitOps.FetchRemote(directory) } func (s *GitHubServiceImpl) SyncWithRemote(directory, branch string, importExcludes []string) error { - fn := zap.String("function", "SyncWithRemote") - - // Preserve excluded directories across the hard reset. - // The normalization commit tracks these files locally, but they - // are filtered from the API commit and absent on the remote — - // so git reset --hard would delete them. - excludes := mergeExcludes(importExcludes) - preserved := s.preserveExcludedDirs(directory, excludes, fn) - - if err := s.FetchRemote(directory); err != nil { - return err - } - - // Reset the working tree and index to match the remote branch. - debugEnabled := s.logger.Core().Enabled(zapcore.DebugLevel) - ref := "origin/" + branch - resetCmd := newGitCommand(s.executor("git", "reset", "--hard", ref), directory, debugEnabled, true) - if err := resetCmd.run(); err != nil { - return fmt.Errorf("failed to reset to %s: %w, stderr: %s", ref, err, resetCmd.getStderr()) - } - s.logger.Debug("git reset --hard", fn, zap.String("ref", ref), zap.String("stdout", resetCmd.getStdout()), zap.String("stderr", resetCmd.getStderr())) - - // Restore preserved directories after the reset. - s.restoreExcludedDirs(directory, preserved, fn) - - return nil + return s.gitOps.SyncWithRemote(directory, branch, importExcludes) } -// preserveExcludedDirs moves excluded artifact directories to temporary -// names so they survive a git reset --hard. Returns the list of -// directory base names that were successfully preserved. -func (s *GitHubServiceImpl) preserveExcludedDirs(directory string, excludes []string, fn zapcore.Field) []string { - var preserved []string - for _, prefix := range excludes { - dir := strings.TrimSuffix(prefix, "/") - src := filepath.Join(directory, dir) - dst := filepath.Join(directory, dir+".preserve") - - if _, err := os.Stat(src); err != nil { - continue - } - _ = os.RemoveAll(dst) // clean up any stale preserve dir - if err := os.Rename(src, dst); err != nil { - s.logger.Warn("Failed to preserve directory", fn, - zap.String("dir", dir), zap.Error(err)) - continue - } - preserved = append(preserved, dir) - } - return preserved -} - -// restoreExcludedDirs moves preserved artifact directories back to -// their original names after a git reset --hard. -func (s *GitHubServiceImpl) restoreExcludedDirs(directory string, preserved []string, fn zapcore.Field) { - for _, dir := range preserved { - src := filepath.Join(directory, dir+".preserve") - dst := filepath.Join(directory, dir) - if err := os.Rename(src, dst); err != nil { - s.logger.Warn("Failed to restore directory", fn, - zap.String("dir", dir), zap.Error(err)) - } - } -} // ReplyToComment replies to a specific PR review comment. // For line-based review comments, this creates a threaded reply. @@ -2048,26 +1748,7 @@ func (s *GitHubServiceImpl) AddCommentReaction(owner, repo string, comment model // non-empty, the specified branch/tag/commit is checked out. This is a // shallow clone (depth 1) since import repos are read-only references. func (s *GitHubServiceImpl) CloneImport(url, destDir, ref string) error { - args := []string{"clone", "--depth", "1"} - if ref != "" { - args = append(args, "--branch", ref) - } - args = append(args, url, destDir) - - cmd := s.executor("git", args...) - var stderr bytes.Buffer - cmd.Stderr = &stderr - - if err := cmd.Run(); err != nil { - return fmt.Errorf("git clone %s into %s: %w, stderr: %s", url, destDir, err, stderr.String()) - } - - s.logger.Debug("Cloned import repo", - zap.String("url", url), - zap.String("dest", destDir), - zap.String("ref", ref)) - - return nil + return s.gitOps.CloneImport(url, destDir, ref) } // fetchPRReviewCommentsPage fetches a single page of PR review comments @@ -2812,46 +2493,7 @@ func (s *GitHubServiceImpl) SyncFork(forkOwner, repo, branch string) error { // and the list of conflicted file paths (conflict markers are left // in the working tree). func (s *GitHubServiceImpl) MergeBase(dir, branch, fetchURL string) ([]string, error) { - remote := "origin" - mergeRef := "origin/" + branch - if fetchURL != "" { - remote = fetchURL - mergeRef = "FETCH_HEAD" - } - fetchCmd := s.executor("git", "fetch", remote, branch) - fetchCmd.Dir = dir - if _, err := fetchCmd.CombinedOutput(); err != nil { - return nil, fmt.Errorf("git fetch %s %s: %w", remote, branch, err) - } - - mergeOut, err := s.runMerge(dir, mergeRef) - if blockers := parseUntrackedBlockers(string(mergeOut)); err != nil && len(blockers) > 0 { - s.logger.Info("Removing untracked files blocking merge", - zap.Strings("files", blockers)) - args := append([]string{"clean", "-f", "--"}, blockers...) - cleanCmd := s.executor("git", args...) - cleanCmd.Dir = dir - if cleanOut, cleanErr := cleanCmd.CombinedOutput(); cleanErr != nil { - return nil, fmt.Errorf("git clean blocking paths: %w, output: %s", cleanErr, string(cleanOut)) - } - mergeOut, err = s.runMerge(dir, mergeRef) - } - if err != nil { - conflictFiles := s.listConflictFiles(dir) - if len(conflictFiles) > 0 { - return conflictFiles, fmt.Errorf("%w: conflicted files: %v", ErrMergeConflict, conflictFiles) - } - return nil, fmt.Errorf("git merge %s failed: %w, output: %s", mergeRef, err, string(mergeOut)) - } - - return []string{}, nil -} - -func (s *GitHubServiceImpl) runMerge(dir, mergeRef string) ([]byte, error) { - mergeCmd := s.executor("git", "merge", "--no-edit", mergeRef) - mergeCmd.Dir = dir - out, err := mergeCmd.CombinedOutput() - return out, err + return s.gitOps.MergeBase(dir, branch, fetchURL) } // parseUntrackedBlockers extracts file paths from git's @@ -2877,32 +2519,6 @@ func parseUntrackedBlockers(output string) []string { return paths } -// listConflictFiles returns file paths with unresolved merge conflicts -// by parsing git status porcelain output for unmerged entries. -func (s *GitHubServiceImpl) listConflictFiles(dir string) []string { - cmd := s.executor("git", "status", "--porcelain") - cmd.Dir = dir - out, err := cmd.Output() - if err != nil { - return []string{} - } - - var files []string - for _, line := range strings.Split(string(out), "\n") { - if len(line) < 4 { - continue - } - xy := line[:2] - if xy == "UU" || xy == "AA" || xy == "DD" || - xy == "AU" || xy == "UA" || xy == "DU" || xy == "UD" { - files = append(files, strings.TrimSpace(line[3:])) - } - } - if files == nil { - files = []string{} - } - return files -} // GetPRMergeability fetches the mergeability status of a pull request. // GitHub computes mergeability asynchronously; the first GET triggers diff --git a/services/gitlab.go b/services/gitlab.go new file mode 100644 index 0000000..39a9dc6 --- /dev/null +++ b/services/gitlab.go @@ -0,0 +1,935 @@ +package services + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + + "jira-ai-issue-solver/models" +) + +// GitLabServiceImpl is the concrete implementation for GitLab operations. +// It satisfies the same consumer-defined interfaces as GitHubServiceImpl, +// enabling per-project hosting selection via the hosting router. +type GitLabServiceImpl struct { + config *models.Config + client *http.Client + executor models.CommandExecutor + logger *zap.Logger + gitOps *GitOps +} + +// NewGitLabService creates a new GitLabServiceImpl. +func NewGitLabService(config *models.Config, logger *zap.Logger, executor ...models.CommandExecutor) *GitLabServiceImpl { + commandExecutor := exec.Command + if len(executor) > 0 { + commandExecutor = executor[0] + } + + return &GitLabServiceImpl{ + config: config, + client: &http.Client{Timeout: 30 * time.Second}, + executor: commandExecutor, + logger: logger, + gitOps: NewGitOps(commandExecutor, logger), + } +} + +// --- Git operations (delegated to shared GitOps) --- + +func (s *GitLabServiceImpl) CreateBranch(directory, branchName, baseBranch string) error { + return s.gitOps.CreateBranch(directory, branchName, baseBranch) +} + +func (s *GitLabServiceImpl) SwitchBranch(directory, branchName string) error { + return s.gitOps.SwitchBranch(directory, branchName) +} + +func (s *GitLabServiceImpl) HasChanges(directory, baseBranch string) (bool, error) { + return s.gitOps.HasChanges(directory, baseBranch) +} + +func (s *GitLabServiceImpl) StripRemoteAuth(directory string) error { + return s.gitOps.StripRemoteAuth(directory) +} + +func (s *GitLabServiceImpl) FetchRemote(directory string) error { + return s.gitOps.FetchRemote(directory) +} + +func (s *GitLabServiceImpl) SyncWithRemote(directory, branch string, importExcludes []string) error { + return s.gitOps.SyncWithRemote(directory, branch, importExcludes) +} + +func (s *GitLabServiceImpl) MergeBase(dir, branch, fetchURL string) ([]string, error) { + return s.gitOps.MergeBase(dir, branch, fetchURL) +} + +func (s *GitLabServiceImpl) CloneImport(url, destDir, ref string) error { + return s.gitOps.CloneImport(url, destDir, ref) +} + +// --- Provider-specific operations --- + +func (s *GitLabServiceImpl) RestoreRemoteAuth(directory, owner, repo string) error { + token := s.config.GitLab.AccessToken + baseURL := strings.TrimSuffix(s.config.GitLab.BaseURL, "/") + authURL := fmt.Sprintf("%s/oauth2:%s@%s/%s/%s.git", + strings.Replace(baseURL, "https://", "https://", 1), + token, + strings.TrimPrefix(strings.TrimPrefix(baseURL, "https://"), "http://"), + owner, repo) + + return s.gitOps.SetRemoteURL(directory, authURL) +} + +func (s *GitLabServiceImpl) SyncFork(forkOwner, repo, branch string) error { + // GitLab fork sync: PUT /projects/:id/fork (no direct equivalent to + // GitHub's merge-upstream). For now, this is a no-op — the clone + // fetches from upstream before branching which achieves the same. + s.logger.Debug("SyncFork is a no-op for GitLab (handled by fetch)", + zap.String("forkOwner", forkOwner), + zap.String("repo", repo), + zap.String("branch", branch)) + return nil +} + +func (s *GitLabServiceImpl) RemoteBranchExists(owner, repo, branch string) (bool, error) { + projectID := s.projectPath(owner, repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/repository/branches/%s", + s.config.GitLab.BaseURL, projectID, branch) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return false, fmt.Errorf("check branch existence: %w", err) + } + defer resp.Body.Close() + + switch resp.StatusCode { + case http.StatusOK: + return true, nil + case http.StatusNotFound: + return false, nil + default: + return false, fmt.Errorf("unexpected status %d checking branch %s", resp.StatusCode, branch) + } +} + +func (s *GitLabServiceImpl) DeleteRemoteBranch(owner, repo, branch string) error { + projectID := s.projectPath(owner, repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/repository/branches/%s", + s.config.GitLab.BaseURL, projectID, branch) + + resp, err := s.doRequest("DELETE", url, nil) + if err != nil { + return fmt.Errorf("delete branch: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode == http.StatusNotFound { + return nil + } + if resp.StatusCode >= 300 { + body, _ := io.ReadAll(resp.Body) + return fmt.Errorf("delete branch %s: status %d, body: %s", branch, resp.StatusCode, string(body)) + } + return nil +} + +// CommitChanges for GitLab: stage, commit locally, and git push. Returns +// the commit SHA from the push. The upstreamOwner parameter is ignored +// (only relevant for GitHub's Git Data API fork resolution). +func (s *GitLabServiceImpl) CommitChanges(upstreamOwner, owner, repo, branch, message, dir, baseBranch string, + coAuthor *models.Author, importExcludes []string, skipFileGuardrail ...bool) (string, error) { + + fn := zap.String("function", "CommitChanges") + + // Stage and commit locally. + if err := s.gitOps.StageAndCommitLocal(dir, fn); err != nil { + return "", err + } + + // Check if there are commits to push. + hasChanges, err := s.gitOps.HasChanges(dir, baseBranch) + if err != nil { + return "", fmt.Errorf("check changes: %w", err) + } + if !hasChanges { + return "", ErrNoChanges + } + + // Amend the last commit with the proper message and co-author. + commitMsg := message + if coAuthor != nil && coAuthor.Name != "" && coAuthor.Email != "" { + commitMsg += fmt.Sprintf("\n\nCo-authored-by: %s <%s>", coAuthor.Name, coAuthor.Email) + } + + debugEnabled := s.logger.Core().Enabled(zapcore.DebugLevel) + + amendCmd := newGitCommand( + s.executor("git", "commit", "--amend", "-m", commitMsg), + dir, debugEnabled, true) + if err := amendCmd.run(); err != nil { + return "", fmt.Errorf("git commit --amend: %w, stderr: %s", err, amendCmd.getStderr()) + } + + // Restore auth for push. + if err := s.RestoreRemoteAuth(dir, owner, repo); err != nil { + return "", fmt.Errorf("restore auth for push: %w", err) + } + + // Push to remote (force push since we amend). + pushCmd := newGitCommand( + s.executor("git", "push", "--force", "origin", branch), + dir, debugEnabled, true) + if err := pushCmd.run(); err != nil { + return "", fmt.Errorf("git push: %w, stderr: %s", err, pushCmd.getStderr()) + } + + // Get the SHA of HEAD after push. + shaCmd := newGitCommand( + s.executor("git", "rev-parse", "HEAD"), + dir, true, true) + if err := shaCmd.run(); err != nil { + return "", fmt.Errorf("get commit SHA: %w", err) + } + + return strings.TrimSpace(shaCmd.getStdout()), nil +} + +func (s *GitLabServiceImpl) CloneRepository(repoURL, directory string) error { + if err := os.MkdirAll(directory, 0750); err != nil { + return fmt.Errorf("failed to create directory: %w", err) + } + + debugEnabled := s.logger.Core().Enabled(zapcore.DebugLevel) + fn := zap.String("function", "CloneRepository") + + if _, err := os.Stat(filepath.Join(directory, ".git")); err == nil { + cmd := newGitCommand(s.executor("git", "fetch", "origin"), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to fetch repository: %w, stderr: %s", err, cmd.getStderr()) + } + s.logger.Debug("git fetch origin", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + cmd = newGitCommand(s.executor("git", "reset", "--hard", "origin/main"), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + cmd = newGitCommand(s.executor("git", "reset", "--hard", "origin/master"), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to reset to origin/main or origin/master: %w, stderr: %s", err, cmd.getStderr()) + } + } + + cmd = newGitCommand(s.executor("git", "clean", "-fdx"), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to clean repository: %w, stderr: %s", err, cmd.getStderr()) + } + } else { + // Inject token into clone URL for auth. + authRepoURL := s.injectAuth(repoURL) + cmd := newGitCommand(s.executor("git", "clone", authRepoURL, directory), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to clone repository: %w, stderr: %s", err, cmd.getStderr()) + } + s.logger.Debug("git clone", fn) + } + + if err := s.gitOps.ConfigureUser(directory, s.config.GitLab.BotUsername, s.config.GitLab.BotEmail); err != nil { + return err + } + + if err := s.gitOps.ConfigureSSHSigning(directory, s.config.GitLab.SSHKeyPath); err != nil { + return err + } + + // Set remote URL with auth token. + owner, repo, err := extractGitLabRepoInfo(repoURL) + if err != nil { + return fmt.Errorf("failed to extract repo info: %w", err) + } + return s.RestoreRemoteAuth(directory, owner, repo) +} + +// --- Merge Request operations --- + +func (s *GitLabServiceImpl) CreatePR(params models.PRParams) (*models.PR, error) { + projectID := s.projectPath(params.Owner, params.Repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests", s.config.GitLab.BaseURL, projectID) + + body := map[string]interface{}{ + "source_branch": params.Head, + "target_branch": params.Base, + "title": params.Title, + "description": params.Body, + } + if len(params.Labels) > 0 { + body["labels"] = strings.Join(params.Labels, ",") + } + if len(params.Assignees) > 0 { + // GitLab uses user IDs for assignees; for now pass usernames + // and let the caller handle ID resolution upstream. + body["assignee_ids"] = []int{} + } + + resp, err := s.doJSONRequest("POST", url, body) + if err != nil { + return nil, fmt.Errorf("create merge request: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + respBody, _ := io.ReadAll(resp.Body) + return nil, fmt.Errorf("create MR failed: status %d, body: %s", resp.StatusCode, string(respBody)) + } + + var mr struct { + IID int `json:"iid"` + WebURL string `json:"web_url"` + State string `json:"state"` + } + if err := json.NewDecoder(resp.Body).Decode(&mr); err != nil { + return nil, fmt.Errorf("decode MR response: %w", err) + } + + return &models.PR{ + Number: mr.IID, + URL: mr.WebURL, + State: mr.State, + }, nil +} + +func (s *GitLabServiceImpl) GetPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + return s.findMRByBranch(owner, repo, head, "opened") +} + +func (s *GitLabServiceImpl) GetClosedPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + return s.findMRByBranch(owner, repo, head, "closed") +} + +func (s *GitLabServiceImpl) GetMergedPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + return s.findMRByBranch(owner, repo, head, "merged") +} + +func (s *GitLabServiceImpl) findMRByBranch(owner, repo, head, state string) (*models.PRDetails, error) { + projectID := s.projectPath(owner, repo) + // Strip fork owner prefix if present (e.g., "forkuser:branch" → "branch"). + branch := head + if idx := strings.Index(head, ":"); idx >= 0 { + branch = head[idx+1:] + } + + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests?source_branch=%s&state=%s&per_page=1", + s.config.GitLab.BaseURL, projectID, branch, state) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("find MR by branch: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("find MR: unexpected status %d", resp.StatusCode) + } + + var mrs []struct { + IID int `json:"iid"` + Title string `json:"title"` + SourceBranch string `json:"source_branch"` + TargetBranch string `json:"target_branch"` + WebURL string `json:"web_url"` + SHA string `json:"sha"` + CreatedAt string `json:"created_at"` + } + if err := json.NewDecoder(resp.Body).Decode(&mrs); err != nil { + return nil, fmt.Errorf("decode MR list: %w", err) + } + + if len(mrs) == 0 { + return nil, nil + } + + mr := mrs[0] + createdAt, _ := time.Parse(time.RFC3339, mr.CreatedAt) + return &models.PRDetails{ + Number: mr.IID, + Title: mr.Title, + Branch: mr.SourceBranch, + BaseBranch: mr.TargetBranch, + URL: mr.WebURL, + HeadSHA: mr.SHA, + CreatedAt: createdAt, + }, nil +} + +func (s *GitLabServiceImpl) GetPRComments(owner, repo string, number int, since time.Time) ([]models.PRComment, error) { + projectID := s.projectPath(owner, repo) + var allComments []models.PRComment + page := 1 + + for { + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d/notes?per_page=100&page=%d&sort=asc", + s.config.GitLab.BaseURL, projectID, number, page) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("get MR notes: %w", err) + } + + var notes []struct { + ID int64 `json:"id"` + Body string `json:"body"` + Author struct { + Username string `json:"username"` + } `json:"author"` + CreatedAt string `json:"created_at"` + System bool `json:"system"` + Resolvable bool `json:"resolvable"` + Position *struct { + NewPath string `json:"new_path"` + NewLine int `json:"new_line"` + } `json:"position"` + } + if err := json.NewDecoder(resp.Body).Decode(¬es); err != nil { + resp.Body.Close() + return nil, fmt.Errorf("decode MR notes: %w", err) + } + resp.Body.Close() + + for _, note := range notes { + if note.System { + continue + } + ts, _ := time.Parse(time.RFC3339, note.CreatedAt) + if !since.IsZero() && ts.Before(since) { + continue + } + + comment := models.PRComment{ + ID: note.ID, + Author: models.Author{Name: note.Author.Username}, + Body: note.Body, + URL: fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d#note_%d", + s.config.GitLab.BaseURL, projectID, number, note.ID), + Timestamp: ts, + IsReviewComment: note.Resolvable, + } + if note.Position != nil { + comment.FilePath = note.Position.NewPath + comment.Line = note.Position.NewLine + } + allComments = append(allComments, comment) + } + + if len(notes) < 100 { + break + } + page++ + } + + if allComments == nil { + allComments = []models.PRComment{} + } + return allComments, nil +} + +func (s *GitLabServiceImpl) ReplyToComment(owner, repo string, prNumber int, commentID int64, body string) error { + projectID := s.projectPath(owner, repo) + + // Find the discussion containing this note to reply in thread. + discussionID, err := s.findDiscussionForNote(projectID, prNumber, commentID) + if err != nil || discussionID == "" { + // Fall back to posting a new note referencing the original. + return s.PostIssueComment(owner, repo, prNumber, body) + } + + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d/discussions/%s/notes", + s.config.GitLab.BaseURL, projectID, prNumber, discussionID) + + reqBody := map[string]interface{}{"body": body} + resp, err := s.doJSONRequest("POST", url, reqBody) + if err != nil { + return fmt.Errorf("reply to comment: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + respBody, _ := io.ReadAll(resp.Body) + return fmt.Errorf("reply to comment: status %d, body: %s", resp.StatusCode, string(respBody)) + } + return nil +} + +func (s *GitLabServiceImpl) PostIssueComment(owner, repo string, prNumber int, body string) error { + projectID := s.projectPath(owner, repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d/notes", + s.config.GitLab.BaseURL, projectID, prNumber) + + reqBody := map[string]interface{}{"body": body} + resp, err := s.doJSONRequest("POST", url, reqBody) + if err != nil { + return fmt.Errorf("post MR note: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + respBody, _ := io.ReadAll(resp.Body) + return fmt.Errorf("post MR note: status %d, body: %s", resp.StatusCode, string(respBody)) + } + return nil +} + +func (s *GitLabServiceImpl) ListIssueComments(owner, repo string, prNumber int) ([]models.IssueComment, error) { + projectID := s.projectPath(owner, repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d/notes?per_page=100&sort=asc", + s.config.GitLab.BaseURL, projectID, prNumber) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("list MR notes: %w", err) + } + defer resp.Body.Close() + + var notes []struct { + ID int64 `json:"id"` + Body string `json:"body"` + Author struct { + Username string `json:"username"` + } `json:"author"` + System bool `json:"system"` + } + if err := json.NewDecoder(resp.Body).Decode(¬es); err != nil { + return nil, fmt.Errorf("decode MR notes: %w", err) + } + + var comments []models.IssueComment + for _, note := range notes { + if note.System { + continue + } + comments = append(comments, models.IssueComment{ + ID: note.ID, + Body: note.Body, + }) + } + if comments == nil { + comments = []models.IssueComment{} + } + return comments, nil +} + +func (s *GitLabServiceImpl) UpdateIssueComment(owner, repo string, commentID int64, body string) error { + projectID := s.projectPath(owner, repo) + // GitLab's note update requires the MR IID, which we don't have here. + // Use the notes API which accepts note ID at project level. + url := fmt.Sprintf("%s/api/v4/projects/%s/notes/%d", + s.config.GitLab.BaseURL, projectID, commentID) + + reqBody := map[string]interface{}{"body": body} + resp, err := s.doJSONRequest("PUT", url, reqBody) + if err != nil { + return fmt.Errorf("update note: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + respBody, _ := io.ReadAll(resp.Body) + return fmt.Errorf("update note: status %d, body: %s", resp.StatusCode, string(respBody)) + } + return nil +} + +func (s *GitLabServiceImpl) AddCommentReaction(owner, repo string, comment models.PRComment, reaction string) error { + projectID := s.projectPath(owner, repo) + // GitLab award emoji API for MR notes. + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d/notes/%d/award_emoji", + s.config.GitLab.BaseURL, projectID, 0, comment.ID) + // We don't have the MR IID from the comment alone; best-effort skip. + s.logger.Debug("AddCommentReaction skipped (MR IID not available from comment)", + zap.String("owner", owner), zap.String("repo", repo)) + _ = url + return nil +} + +// --- Label operations --- + +func (s *GitLabServiceImpl) AddPRLabel(owner, repo string, number int, label string) error { + return s.updateMRLabels(owner, repo, number, label, true) +} + +func (s *GitLabServiceImpl) RemovePRLabel(owner, repo string, number int, label string) error { + return s.updateMRLabels(owner, repo, number, label, false) +} + +func (s *GitLabServiceImpl) HasPRLabel(owner, repo string, number int, label string) (bool, error) { + projectID := s.projectPath(owner, repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d", + s.config.GitLab.BaseURL, projectID, number) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return false, fmt.Errorf("get MR: %w", err) + } + defer resp.Body.Close() + + var mr struct { + Labels []string `json:"labels"` + } + if err := json.NewDecoder(resp.Body).Decode(&mr); err != nil { + return false, fmt.Errorf("decode MR: %w", err) + } + + for _, l := range mr.Labels { + if l == label { + return true, nil + } + } + return false, nil +} + +func (s *GitLabServiceImpl) LastLabelRemoval(owner, repo string, number int, label string) (time.Time, error) { + // GitLab doesn't have a direct "label events" API equivalent to + // GitHub's timeline events. Return zero time (never removed). + return time.Time{}, nil +} + +// --- CI operations --- + +func (s *GitLabServiceImpl) ListCheckRunsForRef(owner, repo, ref string) ([]models.CheckRunFailure, bool, error) { + projectID := s.projectPath(owner, repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/pipelines?sha=%s&per_page=1", + s.config.GitLab.BaseURL, projectID, ref) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return nil, false, fmt.Errorf("list pipelines: %w", err) + } + defer resp.Body.Close() + + var pipelines []struct { + ID int `json:"id"` + Status string `json:"status"` + } + if err := json.NewDecoder(resp.Body).Decode(&pipelines); err != nil { + return nil, false, fmt.Errorf("decode pipelines: %w", err) + } + + if len(pipelines) == 0 { + return []models.CheckRunFailure{}, true, nil + } + + pipeline := pipelines[0] + allComplete := pipeline.Status != "running" && pipeline.Status != "pending" && pipeline.Status != "created" + + if pipeline.Status == "success" { + return []models.CheckRunFailure{}, allComplete, nil + } + + // Get failed jobs from the pipeline. + jobsURL := fmt.Sprintf("%s/api/v4/projects/%s/pipelines/%d/jobs?scope[]=failed&per_page=100", + s.config.GitLab.BaseURL, projectID, pipeline.ID) + + jobsResp, err := s.doRequest("GET", jobsURL, nil) + if err != nil { + return nil, allComplete, fmt.Errorf("list pipeline jobs: %w", err) + } + defer jobsResp.Body.Close() + + var jobs []struct { + ID int `json:"id"` + Name string `json:"name"` + } + if err := json.NewDecoder(jobsResp.Body).Decode(&jobs); err != nil { + return nil, allComplete, fmt.Errorf("decode pipeline jobs: %w", err) + } + + var failures []models.CheckRunFailure + for _, job := range jobs { + failures = append(failures, models.CheckRunFailure{ + ID: int64(job.ID), + Name: job.Name, + }) + } + if failures == nil { + failures = []models.CheckRunFailure{} + } + return failures, allComplete, nil +} + +func (s *GitLabServiceImpl) ListCheckRunAnnotations(owner, repo string, checkRunID int64) ([]models.CheckAnnotation, error) { + // GitLab doesn't have an equivalent to GitHub check run annotations. + return []models.CheckAnnotation{}, nil +} + +func (s *GitLabServiceImpl) GetFailedJobLogs(owner, repo, headSHA string, maxBytesPerStep int) (map[string][]models.FailedStep, error) { + projectID := s.projectPath(owner, repo) + + // Find pipeline for SHA. + url := fmt.Sprintf("%s/api/v4/projects/%s/pipelines?sha=%s&per_page=1", + s.config.GitLab.BaseURL, projectID, headSHA) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return map[string][]models.FailedStep{}, fmt.Errorf("list pipelines: %w", err) + } + defer resp.Body.Close() + + var pipelines []struct { + ID int `json:"id"` + } + if err := json.NewDecoder(resp.Body).Decode(&pipelines); err != nil { + return map[string][]models.FailedStep{}, nil + } + + if len(pipelines) == 0 { + return map[string][]models.FailedStep{}, nil + } + + // Get failed jobs. + jobsURL := fmt.Sprintf("%s/api/v4/projects/%s/pipelines/%d/jobs?scope[]=failed&per_page=100", + s.config.GitLab.BaseURL, projectID, pipelines[0].ID) + + jobsResp, err := s.doRequest("GET", jobsURL, nil) + if err != nil { + return map[string][]models.FailedStep{}, nil + } + defer jobsResp.Body.Close() + + var jobs []struct { + ID int `json:"id"` + Name string `json:"name"` + } + if err := json.NewDecoder(jobsResp.Body).Decode(&jobs); err != nil { + return map[string][]models.FailedStep{}, nil + } + + result := make(map[string][]models.FailedStep) + for _, job := range jobs { + logURL := fmt.Sprintf("%s/api/v4/projects/%s/jobs/%d/trace", + s.config.GitLab.BaseURL, projectID, job.ID) + + logResp, err := s.doRequest("GET", logURL, nil) + if err != nil { + continue + } + logBytes, _ := io.ReadAll(io.LimitReader(logResp.Body, int64(maxBytesPerStep))) + logResp.Body.Close() + + result[job.Name] = []models.FailedStep{{ + JobName: job.Name, + StepName: job.Name, + Log: string(logBytes), + }} + } + return result, nil +} + +// --- Recovery interface --- + +func (s *GitLabServiceImpl) BranchHasCommits(owner, repo, branch, base string) (bool, error) { + projectID := s.projectPath(owner, repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/repository/compare?from=%s&to=%s", + s.config.GitLab.BaseURL, projectID, base, branch) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return false, fmt.Errorf("compare branches: %w", err) + } + defer resp.Body.Close() + + var comparison struct { + Commits []struct{} `json:"commits"` + } + if err := json.NewDecoder(resp.Body).Decode(&comparison); err != nil { + return false, fmt.Errorf("decode comparison: %w", err) + } + + return len(comparison.Commits) > 0, nil +} + +// --- Mergeability --- + +func (s *GitLabServiceImpl) GetPRMergeability(owner, repo string, number int) (*models.PRMergeState, error) { + projectID := s.projectPath(owner, repo) + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d", + s.config.GitLab.BaseURL, projectID, number) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("get MR mergeability: %w", err) + } + defer resp.Body.Close() + + var mr struct { + MergeStatus string `json:"merge_status"` + TargetBranch string `json:"target_branch"` + HasConflicts bool `json:"has_conflicts"` + } + if err := json.NewDecoder(resp.Body).Decode(&mr); err != nil { + return nil, fmt.Errorf("decode MR: %w", err) + } + + mergeable := !mr.HasConflicts && mr.MergeStatus == "can_be_merged" + return &models.PRMergeState{ + Mergeable: &mergeable, + BaseBranch: mr.TargetBranch, + }, nil +} + +// --- Internal helpers --- + +// projectPath returns the URL-encoded project path for GitLab API calls. +func (s *GitLabServiceImpl) projectPath(owner, repo string) string { + return strings.ReplaceAll(owner+"/"+repo, "/", "%2F") +} + +// injectAuth injects the PAT into a clone URL for authenticated operations. +func (s *GitLabServiceImpl) injectAuth(repoURL string) string { + token := s.config.GitLab.AccessToken + baseURL := s.config.GitLab.BaseURL + + // Transform https://gitlab.com/org/repo.git → + // https://oauth2:token@gitlab.com/org/repo.git + host := strings.TrimPrefix(strings.TrimPrefix(baseURL, "https://"), "http://") + if strings.Contains(repoURL, host) { + return strings.Replace(repoURL, host, fmt.Sprintf("oauth2:%s@%s", token, host), 1) + } + return repoURL +} + +func (s *GitLabServiceImpl) doRequest(method, url string, body io.Reader) (*http.Response, error) { + req, err := http.NewRequest(method, url, body) + if err != nil { + return nil, err + } + req.Header.Set("PRIVATE-TOKEN", s.config.GitLab.AccessToken) + return s.client.Do(req) +} + +func (s *GitLabServiceImpl) doJSONRequest(method, url string, body interface{}) (*http.Response, error) { + jsonBody, err := json.Marshal(body) + if err != nil { + return nil, fmt.Errorf("marshal request body: %w", err) + } + req, err := http.NewRequest(method, url, bytes.NewReader(jsonBody)) + if err != nil { + return nil, err + } + req.Header.Set("PRIVATE-TOKEN", s.config.GitLab.AccessToken) + req.Header.Set("Content-Type", "application/json") + return s.client.Do(req) +} + +func (s *GitLabServiceImpl) updateMRLabels(owner, repo string, number int, label string, add bool) error { + projectID := s.projectPath(owner, repo) + + // First get current labels. + getURL := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d", + s.config.GitLab.BaseURL, projectID, number) + + resp, err := s.doRequest("GET", getURL, nil) + if err != nil { + return fmt.Errorf("get MR labels: %w", err) + } + defer resp.Body.Close() + + var mr struct { + Labels []string `json:"labels"` + } + if err := json.NewDecoder(resp.Body).Decode(&mr); err != nil { + return fmt.Errorf("decode MR: %w", err) + } + + var newLabels []string + if add { + for _, l := range mr.Labels { + if l == label { + return nil + } + } + newLabels = append(mr.Labels, label) + } else { + for _, l := range mr.Labels { + if l != label { + newLabels = append(newLabels, l) + } + } + if len(newLabels) == len(mr.Labels) { + return nil + } + } + + // Update labels. + putURL := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d", + s.config.GitLab.BaseURL, projectID, number) + + reqBody := map[string]interface{}{ + "labels": strings.Join(newLabels, ","), + } + putResp, err := s.doJSONRequest("PUT", putURL, reqBody) + if err != nil { + return fmt.Errorf("update MR labels: %w", err) + } + defer putResp.Body.Close() + + if putResp.StatusCode >= 300 { + respBody, _ := io.ReadAll(putResp.Body) + return fmt.Errorf("update MR labels: status %d, body: %s", putResp.StatusCode, string(respBody)) + } + return nil +} + +func (s *GitLabServiceImpl) findDiscussionForNote(projectID string, mrIID int, noteID int64) (string, error) { + url := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests/%d/discussions?per_page=100", + s.config.GitLab.BaseURL, projectID, mrIID) + + resp, err := s.doRequest("GET", url, nil) + if err != nil { + return "", err + } + defer resp.Body.Close() + + var discussions []struct { + ID string `json:"id"` + Notes []struct { + ID int64 `json:"id"` + } `json:"notes"` + } + if err := json.NewDecoder(resp.Body).Decode(&discussions); err != nil { + return "", err + } + + for _, d := range discussions { + for _, n := range d.Notes { + if n.ID == noteID { + return d.ID, nil + } + } + } + return "", nil +} + +// extractGitLabRepoInfo extracts the owner/group and repo name from a GitLab URL. +func extractGitLabRepoInfo(repoURL string) (string, string, error) { + repoURL = strings.TrimSuffix(repoURL, ".git") + // Handle https://gitlab.com/org/subgroup/repo format. + parts := strings.Split(repoURL, "/") + if len(parts) < 5 { + return "", "", fmt.Errorf("cannot extract owner/repo from GitLab URL: %s", repoURL) + } + repo := parts[len(parts)-1] + // Owner is everything between the host and the repo name. + hostIdx := 3 // after https://host/ + owner := strings.Join(parts[hostIdx:len(parts)-1], "/") + return owner, repo, nil +} + diff --git a/services/gitlab_test.go b/services/gitlab_test.go new file mode 100644 index 0000000..4fe4ada --- /dev/null +++ b/services/gitlab_test.go @@ -0,0 +1,346 @@ +package services + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "go.uber.org/zap" + + "jira-ai-issue-solver/models" +) + +func newTestGitLabConfig(baseURL string) *models.Config { + return &models.Config{ + GitLab: struct { + BaseURL string `yaml:"base_url" mapstructure:"base_url"` + AccessToken string `yaml:"access_token" mapstructure:"access_token"` + BotUsername string `yaml:"bot_username" mapstructure:"bot_username"` + BotEmail string `yaml:"bot_email" mapstructure:"bot_email"` + MRLabel string `yaml:"mr_label" mapstructure:"mr_label"` + SSHKeyPath string `yaml:"ssh_key_path" mapstructure:"ssh_key_path"` + SkipMRLabel string `yaml:"skip_mr_label" mapstructure:"skip_mr_label"` + MaxThreadDepth int `yaml:"max_thread_depth" mapstructure:"max_thread_depth"` + KnownBotUsernames []string `yaml:"known_bot_usernames" mapstructure:"known_bot_usernames"` + IgnoredUsernames []string `yaml:"ignored_usernames" mapstructure:"ignored_usernames"` + }{ + BaseURL: baseURL, + AccessToken: "test-token", + BotUsername: "ai-bot", + BotEmail: "ai-bot@example.com", + MRLabel: "ai-mr", + }, + } +} + +func TestGitLabCreatePR(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Errorf("expected POST, got %s", r.Method) + } + if r.Header.Get("PRIVATE-TOKEN") != "test-token" { + t.Errorf("expected auth token, got %s", r.Header.Get("PRIVATE-TOKEN")) + } + + w.WriteHeader(http.StatusCreated) + resp := map[string]interface{}{ + "iid": 42, + "web_url": "https://gitlab.example.com/org/repo/-/merge_requests/42", + "state": "opened", + } + json.NewEncoder(w).Encode(resp) + })) + defer server.Close() + + config := newTestGitLabConfig(server.URL) + logger := zap.NewNop() + svc := NewGitLabService(config, logger) + + pr, err := svc.CreatePR(models.PRParams{ + Owner: "org", + Repo: "repo", + Head: "feature-branch", + Base: "main", + Title: "Test MR", + Body: "Test body", + Labels: []string{"ai-mr"}, + }) + if err != nil { + t.Fatalf("CreatePR failed: %v", err) + } + if pr.Number != 42 { + t.Errorf("expected MR number 42, got %d", pr.Number) + } + if pr.URL != "https://gitlab.example.com/org/repo/-/merge_requests/42" { + t.Errorf("unexpected URL: %s", pr.URL) + } +} + +func TestGitLabGetPRForBranch(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Errorf("expected GET, got %s", r.Method) + } + + resp := []map[string]interface{}{ + { + "iid": 10, + "title": "Feature branch MR", + "source_branch": "feature", + "target_branch": "main", + "web_url": "https://gitlab.example.com/org/repo/-/merge_requests/10", + "sha": "abc123", + "created_at": "2026-01-15T10:00:00Z", + }, + } + json.NewEncoder(w).Encode(resp) + })) + defer server.Close() + + config := newTestGitLabConfig(server.URL) + logger := zap.NewNop() + svc := NewGitLabService(config, logger) + + details, err := svc.GetPRForBranch("org", "repo", "feature") + if err != nil { + t.Fatalf("GetPRForBranch failed: %v", err) + } + if details == nil { + t.Fatal("expected non-nil PRDetails") + } + if details.Number != 10 { + t.Errorf("expected MR IID 10, got %d", details.Number) + } + if details.Branch != "feature" { + t.Errorf("expected source branch 'feature', got %s", details.Branch) + } +} + +func TestGitLabGetPRForBranch_NotFound(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode([]map[string]interface{}{}) + })) + defer server.Close() + + config := newTestGitLabConfig(server.URL) + logger := zap.NewNop() + svc := NewGitLabService(config, logger) + + details, err := svc.GetPRForBranch("org", "repo", "nonexistent") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if details != nil { + t.Error("expected nil for non-existent branch") + } +} + +func TestGitLabGetPRComments(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + resp := []map[string]interface{}{ + { + "id": int64(1), + "body": "Review comment", + "author": map[string]string{"username": "reviewer"}, + "created_at": "2026-01-15T10:00:00Z", + "system": false, + "resolvable": true, + "position": map[string]interface{}{"new_path": "main.go", "new_line": 42}, + }, + { + "id": int64(2), + "body": "System note", + "author": map[string]string{"username": "system"}, + "created_at": "2026-01-15T11:00:00Z", + "system": true, + "resolvable": false, + }, + } + json.NewEncoder(w).Encode(resp) + })) + defer server.Close() + + config := newTestGitLabConfig(server.URL) + logger := zap.NewNop() + svc := NewGitLabService(config, logger) + + comments, err := svc.GetPRComments("org", "repo", 10, time.Time{}) + if err != nil { + t.Fatalf("GetPRComments failed: %v", err) + } + if len(comments) != 1 { + t.Fatalf("expected 1 non-system comment, got %d", len(comments)) + } + if comments[0].Body != "Review comment" { + t.Errorf("unexpected body: %s", comments[0].Body) + } + if comments[0].FilePath != "main.go" { + t.Errorf("unexpected file path: %s", comments[0].FilePath) + } + if comments[0].Line != 42 { + t.Errorf("expected line 42, got %d", comments[0].Line) + } +} + +func TestGitLabListCheckRunsForRef(t *testing.T) { + callCount := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + callCount++ + if callCount == 1 { + resp := []map[string]interface{}{ + {"id": 100, "status": "failed"}, + } + json.NewEncoder(w).Encode(resp) + } else { + resp := []map[string]interface{}{ + {"id": 200, "name": "test-job"}, + } + json.NewEncoder(w).Encode(resp) + } + })) + defer server.Close() + + config := newTestGitLabConfig(server.URL) + logger := zap.NewNop() + svc := NewGitLabService(config, logger) + + failures, allComplete, err := svc.ListCheckRunsForRef("org", "repo", "abc123") + if err != nil { + t.Fatalf("ListCheckRunsForRef failed: %v", err) + } + if !allComplete { + t.Error("expected allComplete=true for 'failed' status") + } + if len(failures) != 1 { + t.Fatalf("expected 1 failure, got %d", len(failures)) + } + if failures[0].Name != "test-job" { + t.Errorf("unexpected job name: %s", failures[0].Name) + } +} + +func TestGitLabAddRemovePRLabel(t *testing.T) { + callCount := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + callCount++ + if r.Method == "GET" { + resp := map[string]interface{}{ + "labels": []string{"existing-label"}, + } + json.NewEncoder(w).Encode(resp) + } else if r.Method == "PUT" { + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]interface{}{}) + } + })) + defer server.Close() + + config := newTestGitLabConfig(server.URL) + logger := zap.NewNop() + svc := NewGitLabService(config, logger) + + err := svc.AddPRLabel("org", "repo", 1, "new-label") + if err != nil { + t.Fatalf("AddPRLabel failed: %v", err) + } + + err = svc.RemovePRLabel("org", "repo", 1, "existing-label") + if err != nil { + t.Fatalf("RemovePRLabel failed: %v", err) + } +} + +func TestGitLabRemoteBranchExists(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]interface{}{"name": "feature"}) + } + })) + defer server.Close() + + config := newTestGitLabConfig(server.URL) + logger := zap.NewNop() + svc := NewGitLabService(config, logger) + + exists, err := svc.RemoteBranchExists("org", "repo", "feature") + if err != nil { + t.Fatalf("RemoteBranchExists failed: %v", err) + } + if !exists { + t.Error("expected branch to exist") + } +} + +func TestGitLabRemoteBranchNotExists(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + + config := newTestGitLabConfig(server.URL) + logger := zap.NewNop() + svc := NewGitLabService(config, logger) + + exists, err := svc.RemoteBranchExists("org", "repo", "nonexistent") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if exists { + t.Error("expected branch to not exist") + } +} + +func TestGitLabCloneRepository(t *testing.T) { + tmpDir := t.TempDir() + repoDir := filepath.Join(tmpDir, "repo") + + // Create a fake git repo. + os.MkdirAll(filepath.Join(repoDir, ".git"), 0750) + + fakeExec := func(name string, args ...string) *exec.Cmd { + return exec.Command("true") + } + + config := newTestGitLabConfig("https://gitlab.example.com") + logger := zap.NewNop() + svc := NewGitLabService(config, logger, fakeExec) + + err := svc.CloneRepository("https://gitlab.example.com/org/repo.git", repoDir) + if err != nil { + t.Fatalf("CloneRepository failed: %v", err) + } +} + +func TestExtractGitLabRepoInfo(t *testing.T) { + tests := []struct { + url string + wantOwner string + wantRepo string + wantErr bool + }{ + {"https://gitlab.com/org/repo.git", "org", "repo", false}, + {"https://gitlab.cee.redhat.com/group/subgroup/repo.git", "group/subgroup", "repo", false}, + {"https://gitlab.com/a/b/c/d.git", "a/b/c", "d", false}, + {"invalid", "", "", true}, + } + + for _, tt := range tests { + owner, repo, err := extractGitLabRepoInfo(tt.url) + if (err != nil) != tt.wantErr { + t.Errorf("extractGitLabRepoInfo(%s): err=%v, wantErr=%v", tt.url, err, tt.wantErr) + continue + } + if owner != tt.wantOwner { + t.Errorf("extractGitLabRepoInfo(%s): owner=%q, want %q", tt.url, owner, tt.wantOwner) + } + if repo != tt.wantRepo { + t.Errorf("extractGitLabRepoInfo(%s): repo=%q, want %q", tt.url, repo, tt.wantRepo) + } + } +} diff --git a/services/gitops.go b/services/gitops.go new file mode 100644 index 0000000..ceee6b7 --- /dev/null +++ b/services/gitops.go @@ -0,0 +1,476 @@ +// Package services provides infrastructure implementations for VCS and issue tracker operations. +// +// gitops.go contains provider-agnostic git operations shared by both +// GitHubServiceImpl and GitLabServiceImpl. These are pure local git +// commands that do not require any platform-specific API calls. +package services + +import ( + "bytes" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + + "jira-ai-issue-solver/models" +) + +// GitOps provides provider-agnostic local git operations. Both +// GitHubServiceImpl and GitLabServiceImpl embed this struct to +// share implementations of CreateBranch, SwitchBranch, HasChanges, +// StripRemoteAuth, FetchRemote, SyncWithRemote, MergeBase, and +// CloneImport. +type GitOps struct { + executor models.CommandExecutor + logger *zap.Logger +} + +// NewGitOps creates a GitOps instance with the given command executor and logger. +func NewGitOps(executor models.CommandExecutor, logger *zap.Logger) *GitOps { + return &GitOps{ + executor: executor, + logger: logger, + } +} + +// CreateBranch creates a new git branch in the workspace and switches to it. +// baseBranch is the branch to fork from (e.g., "main"). If the branch +// already exists locally it is deleted and recreated. +func (g *GitOps) CreateBranch(directory, branchName, baseBranch string) error { + debugEnabled := g.logger.Core().Enabled(zapcore.DebugLevel) + fn := zap.String("function", "CreateBranch") + + resetCmd := newGitCommand(g.executor("git", "reset", "--hard", "HEAD"), directory, debugEnabled, true) + if err := resetCmd.run(); err != nil { + g.logger.Warn("git reset --hard HEAD failed (non-fatal)", + fn, zap.Error(err), zap.String("stderr", resetCmd.getStderr())) + } + + cmd := newGitCommand(g.executor("git", "fetch", "origin"), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to fetch origin: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git fetch origin", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + cmd = newGitCommand(g.executor("git", "checkout", baseBranch), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to checkout target branch %s: %w, stderr: %s", baseBranch, err, cmd.getStderr()) + } + g.logger.Debug("git checkout", fn, zap.String("branch", baseBranch), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + cmd = newGitCommand(g.executor("git", "reset", "--hard", "origin/"+baseBranch), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to reset to latest commit on target branch %s: %w, stderr: %s", baseBranch, err, cmd.getStderr()) + } + g.logger.Debug("git reset --hard", fn, zap.String("ref", "origin/"+baseBranch), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + cmd = newGitCommand(g.executor("git", "show-ref", "--verify", "--quiet", "refs/heads/"+branchName), directory, debugEnabled, true) + if err := cmd.run(); err == nil { + g.logger.Info("Branch already exists locally, deleting it", zap.String("branchName", branchName)) + cmd = newGitCommand(g.executor("git", "branch", "-D", branchName), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to delete existing branch %s: %w, stderr: %s", branchName, err, cmd.getStderr()) + } + g.logger.Debug("git branch -D", fn, zap.String("branch", branchName), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + } + + cmd = newGitCommand(g.executor("git", "checkout", "-b", branchName), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to create branch: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git checkout", fn, zap.String("operation", "-b"), zap.String("branch", branchName), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + return nil +} + +// SwitchBranch switches to an existing branch. Used when a workspace +// is reused on retry or when checking out a PR branch for feedback +// processing. +func (g *GitOps) SwitchBranch(directory, branchName string) error { + debugEnabled := g.logger.Core().Enabled(zapcore.DebugLevel) + fn := zap.String("function", "SwitchBranch") + + resetCmd := newGitCommand(g.executor("git", "reset", "--hard", "HEAD"), directory, debugEnabled, true) + if err := resetCmd.run(); err != nil { + g.logger.Warn("git reset --hard HEAD failed (non-fatal)", + fn, zap.Error(err), zap.String("stderr", resetCmd.getStderr())) + } + + cmd := newGitCommand(g.executor("git", "fetch", "origin"), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to fetch origin: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git fetch origin", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + cmd = newGitCommand(g.executor("git", "checkout", branchName), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to checkout branch %s: %w, stderr: %s", branchName, err, cmd.getStderr()) + } + g.logger.Debug("git checkout", fn, zap.String("branch", branchName), zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + return nil +} + +// HasChanges reports whether the workspace has uncommitted changes or +// unpushed commits relative to the remote branch. +func (g *GitOps) HasChanges(directory, baseBranch string) (bool, error) { + fn := zap.String("function", "HasChanges") + + hasWT, err := g.hasWorkingTreeChanges(directory, fn) + if err != nil { + return false, err + } + if hasWT { + return true, nil + } + + return g.hasUnpushedCommits(directory, baseBranch, fn) +} + +func (g *GitOps) hasWorkingTreeChanges(directory string, fn zapcore.Field) (bool, error) { + cmd := newGitCommand(g.executor("git", "status", "--porcelain"), directory, true, true) + if err := cmd.run(); err != nil { + return false, fmt.Errorf("failed to check git status: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git status --porcelain", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + return cmd.hasStdout(), nil +} + +func (g *GitOps) hasUnpushedCommits(directory, baseBranch string, fn zapcore.Field) (bool, error) { + remoteCmd := newGitCommand(g.executor("git", "remote", "get-url", "origin"), directory, false, false) + if err := remoteCmd.run(); err != nil { + g.logger.Debug("No origin remote configured", fn) + return false, nil + } + + branchCmd := newGitCommand(g.executor("git", "rev-parse", "--abbrev-ref", "HEAD"), directory, true, true) + if err := branchCmd.run(); err != nil { + return false, fmt.Errorf("failed to get current branch: %w, stderr: %s", err, branchCmd.getStderr()) + } + + branchName := strings.TrimSpace(branchCmd.getStdout()) + if branchName == "" { + return false, fmt.Errorf("unable to determine current branch") + } + g.logger.Debug("Current branch", fn, zap.String("branch", branchName)) + + remoteRef := fmt.Sprintf("origin/%s", branchName) + remoteExistsCmd := newGitCommand(g.executor("git", "rev-parse", "--verify", remoteRef), directory, false, false) + if err := remoteExistsCmd.run(); err != nil { + remoteRef = fmt.Sprintf("origin/%s", baseBranch) + g.logger.Debug("Remote branch does not exist, comparing against target branch", fn, + zap.String("branch", branchName), + zap.String("targetRef", remoteRef)) + } + + logCmd := newGitCommand(g.executor("git", "log", fmt.Sprintf("%s..HEAD", remoteRef), "--oneline"), directory, true, true) + if err := logCmd.run(); err != nil { + return false, fmt.Errorf("failed to check unpushed commits: %w, stderr: %s", err, logCmd.getStderr()) + } + g.logger.Debug("git log ref..HEAD", fn, + zap.String("ref", remoteRef), + zap.String("stdout", logCmd.getStdout()), + zap.String("stderr", logCmd.getStderr())) + + return logCmd.hasStdout(), nil +} + +// StageAndCommitLocal ensures all working tree and staged changes are +// committed locally. Normalizes AI session output (committed, staged, +// or unstaged) into a single committed state. +func (g *GitOps) StageAndCommitLocal(directory string, fn zapcore.Field) error { + statusCmd := newGitCommand(g.executor("git", "status", "--porcelain"), directory, true, true) + if err := statusCmd.run(); err != nil { + return fmt.Errorf("git status: %w, stderr: %s", err, statusCmd.getStderr()) + } + if !statusCmd.hasStdout() { + return nil + } + + g.logger.Debug("Staging uncommitted changes", fn) + + addCmd := newGitCommand(g.executor("git", "add", "-A"), directory, false, true) + if err := addCmd.run(); err != nil { + return fmt.Errorf("git add -A: %w, stderr: %s", err, addCmd.getStderr()) + } + + commitCmd := newGitCommand( + g.executor("git", "commit", "-m", "AI changes (local only)"), + directory, false, true) + if err := commitCmd.run(); err != nil { + return fmt.Errorf("git commit: %w, stderr: %s", err, commitCmd.getStderr()) + } + + g.logger.Debug("Committed local changes", fn) + return nil +} + +// StripRemoteAuth removes authentication credentials from the +// workspace's origin remote URL, preventing push operations. +func (g *GitOps) StripRemoteAuth(directory string) error { + cmd := newGitCommand(g.executor("git", "remote", "get-url", "origin"), directory, true, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("get remote URL: %w, stderr: %s", err, cmd.getStderr()) + } + + rawURL := strings.TrimSpace(cmd.getStdout()) + parsed, err := url.Parse(rawURL) + if err != nil { + return fmt.Errorf("parse remote URL: %w", err) + } + parsed.User = nil + + setCmd := newGitCommand( + g.executor("git", "remote", "set-url", "origin", parsed.String()), + directory, false, false) + if err := setCmd.run(); err != nil { + return fmt.Errorf("strip remote auth: %w, stderr: %s", err, setCmd.getStderr()) + } + + g.logger.Debug("Stripped remote auth", zap.String("directory", directory)) + return nil +} + +// FetchRemote fetches all refs from the origin remote. +func (g *GitOps) FetchRemote(directory string) error { + debugEnabled := g.logger.Core().Enabled(zapcore.DebugLevel) + fn := zap.String("function", "FetchRemote") + + fetchCmd := newGitCommand(g.executor("git", "fetch", "origin"), directory, debugEnabled, true) + if err := fetchCmd.run(); err != nil { + return fmt.Errorf("failed to fetch from origin: %w, stderr: %s", err, fetchCmd.getStderr()) + } + g.logger.Debug("git fetch origin", fn, zap.String("stdout", fetchCmd.getStdout()), zap.String("stderr", fetchCmd.getStderr())) + + return nil +} + +// SyncWithRemote reconciles the local workspace with the remote branch +// after an API-created commit. importExcludes lists directories to +// preserve across the hard reset. +func (g *GitOps) SyncWithRemote(directory, branch string, importExcludes []string) error { + fn := zap.String("function", "SyncWithRemote") + + excludes := mergeExcludes(importExcludes) + preserved := g.preserveExcludedDirs(directory, excludes, fn) + + if err := g.FetchRemote(directory); err != nil { + return err + } + + debugEnabled := g.logger.Core().Enabled(zapcore.DebugLevel) + ref := "origin/" + branch + resetCmd := newGitCommand(g.executor("git", "reset", "--hard", ref), directory, debugEnabled, true) + if err := resetCmd.run(); err != nil { + return fmt.Errorf("failed to reset to %s: %w, stderr: %s", ref, err, resetCmd.getStderr()) + } + g.logger.Debug("git reset --hard", fn, zap.String("ref", ref), zap.String("stdout", resetCmd.getStdout()), zap.String("stderr", resetCmd.getStderr())) + + g.restoreExcludedDirs(directory, preserved, fn) + + return nil +} + +// MergeBase merges a base branch into the current branch in the +// workspace. When fetchURL is non-empty, the base branch is fetched +// from that URL. On conflict, returns ErrMergeConflict and the list +// of conflicted file paths. +func (g *GitOps) MergeBase(dir, branch, fetchURL string) ([]string, error) { + remote := "origin" + mergeRef := "origin/" + branch + if fetchURL != "" { + remote = fetchURL + mergeRef = "FETCH_HEAD" + } + fetchCmd := g.executor("git", "fetch", remote, branch) + fetchCmd.Dir = dir + if _, err := fetchCmd.CombinedOutput(); err != nil { + return nil, fmt.Errorf("git fetch %s %s: %w", remote, branch, err) + } + + mergeOut, err := g.runMerge(dir, mergeRef) + if blockers := parseUntrackedBlockers(string(mergeOut)); err != nil && len(blockers) > 0 { + g.logger.Info("Removing untracked files blocking merge", + zap.Strings("files", blockers)) + args := append([]string{"clean", "-f", "--"}, blockers...) + cleanCmd := g.executor("git", args...) + cleanCmd.Dir = dir + if cleanOut, cleanErr := cleanCmd.CombinedOutput(); cleanErr != nil { + return nil, fmt.Errorf("git clean blocking paths: %w, output: %s", cleanErr, string(cleanOut)) + } + mergeOut, err = g.runMerge(dir, mergeRef) + } + if err != nil { + conflictFiles := g.listConflictFiles(dir) + if len(conflictFiles) > 0 { + return conflictFiles, fmt.Errorf("%w: conflicted files: %v", ErrMergeConflict, conflictFiles) + } + return nil, fmt.Errorf("git merge %s failed: %w, output: %s", mergeRef, err, string(mergeOut)) + } + + return []string{}, nil +} + +func (g *GitOps) runMerge(dir, mergeRef string) ([]byte, error) { + mergeCmd := g.executor("git", "merge", "--no-edit", mergeRef) + mergeCmd.Dir = dir + out, err := mergeCmd.CombinedOutput() + return out, err +} + +func (g *GitOps) listConflictFiles(dir string) []string { + cmd := g.executor("git", "status", "--porcelain") + cmd.Dir = dir + out, err := cmd.Output() + if err != nil { + return []string{} + } + + var files []string + for _, line := range strings.Split(string(out), "\n") { + if len(line) < 4 { + continue + } + xy := line[:2] + if xy == "UU" || xy == "AA" || xy == "DD" || + xy == "AU" || xy == "UA" || xy == "DU" || xy == "UD" { + files = append(files, strings.TrimSpace(line[3:])) + } + } + if files == nil { + files = []string{} + } + return files +} + +// CloneImport clones an auxiliary repository into destDir. If ref is +// non-empty, that branch/tag/commit is checked out after cloning. +func (g *GitOps) CloneImport(repoURL, destDir, ref string) error { + args := []string{"clone", "--depth", "1"} + if ref != "" { + args = append(args, "--branch", ref) + } + args = append(args, repoURL, destDir) + + cmd := g.executor("git", args...) + var stderr bytes.Buffer + cmd.Stderr = &stderr + + if err := cmd.Run(); err != nil { + return fmt.Errorf("git clone %s into %s: %w, stderr: %s", repoURL, destDir, err, stderr.String()) + } + + g.logger.Debug("Cloned import repo", + zap.String("url", repoURL), + zap.String("dest", destDir), + zap.String("ref", ref)) + + return nil +} + +func (g *GitOps) preserveExcludedDirs(directory string, excludes []string, fn zapcore.Field) []string { + var preserved []string + for _, prefix := range excludes { + dir := strings.TrimSuffix(prefix, "/") + src := filepath.Join(directory, dir) + dst := filepath.Join(directory, dir+".preserve") + + if _, err := os.Stat(src); err != nil { + continue + } + _ = os.RemoveAll(dst) + if err := os.Rename(src, dst); err != nil { + g.logger.Warn("Failed to preserve directory", fn, + zap.String("dir", dir), zap.Error(err)) + continue + } + preserved = append(preserved, dir) + } + return preserved +} + +func (g *GitOps) restoreExcludedDirs(directory string, preserved []string, fn zapcore.Field) { + for _, dir := range preserved { + src := filepath.Join(directory, dir+".preserve") + dst := filepath.Join(directory, dir) + if err := os.Rename(src, dst); err != nil { + g.logger.Warn("Failed to restore directory", fn, + zap.String("dir", dir), zap.Error(err)) + } + } +} + +// SetRemoteURL sets the origin remote URL for a workspace directory. +func (g *GitOps) SetRemoteURL(directory, remoteURL string) error { + cmd := newGitCommand( + g.executor("git", "remote", "set-url", "origin", remoteURL), + directory, false, false) + if err := cmd.run(); err != nil { + return fmt.Errorf("set remote URL: %w", err) + } + return nil +} + +// ConfigureUser sets git user.name and user.email in the workspace. +func (g *GitOps) ConfigureUser(directory, name, email string) error { + debugEnabled := g.logger.Core().Enabled(zapcore.DebugLevel) + fn := zap.String("function", "ConfigureUser") + + cmd := newGitCommand(g.executor("git", "config", "user.name", name), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to configure git user name: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git config user.name", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + cmd = newGitCommand(g.executor("git", "config", "user.email", email), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to configure git user email: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git config user.email", fn, zap.String("stderr", cmd.getStderr())) + + return nil +} + +// ConfigureSSHSigning configures SSH key signing in the workspace. +// Does nothing if sshKeyPath is empty or the key file does not exist. +func (g *GitOps) ConfigureSSHSigning(directory, sshKeyPath string) error { + if sshKeyPath == "" { + return nil + } + + exists, err := fileExists(sshKeyPath) + if err != nil { + return fmt.Errorf("failed to check if SSH key file exists: %w", err) + } + if !exists { + g.logger.Info("SSH signing not configured for repository") + return nil + } + + debugEnabled := g.logger.Core().Enabled(zapcore.DebugLevel) + fn := zap.String("function", "ConfigureSSHSigning") + + cmd := newGitCommand(g.executor("git", "config", "gpg.format", "ssh"), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to configure git gpg format: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git config gpg.format", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + cmd = newGitCommand(g.executor("git", "config", "user.signingkey", sshKeyPath), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to configure git ssh signing key: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git config user.signingkey", fn, zap.String("stdout", cmd.getStdout()), zap.String("stderr", cmd.getStderr())) + + cmd = newGitCommand(g.executor("git", "config", "commit.gpgsign", "true"), directory, debugEnabled, true) + if err := cmd.run(); err != nil { + return fmt.Errorf("failed to enable git commit signing: %w, stderr: %s", err, cmd.getStderr()) + } + g.logger.Debug("git config commit.gpgsign", fn) + + return nil +} diff --git a/services/gitops_test.go b/services/gitops_test.go new file mode 100644 index 0000000..b764e42 --- /dev/null +++ b/services/gitops_test.go @@ -0,0 +1,126 @@ +package services + +import ( + "os" + "os/exec" + "path/filepath" + "testing" + + "go.uber.org/zap" +) + +func TestGitOps_StripRemoteAuth(t *testing.T) { + tmpDir := t.TempDir() + + // Initialize a git repo with a remote URL containing credentials. + commands := [][]string{ + {"git", "init"}, + {"git", "remote", "add", "origin", "https://token@github.com/org/repo.git"}, + } + for _, args := range commands { + cmd := exec.Command(args[0], args[1:]...) + cmd.Dir = tmpDir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("setup %v failed: %v\n%s", args, err, string(out)) + } + } + + logger := zap.NewNop() + gitOps := NewGitOps(exec.Command, logger) + + if err := gitOps.StripRemoteAuth(tmpDir); err != nil { + t.Fatalf("StripRemoteAuth failed: %v", err) + } + + // Verify credentials were removed. + cmd := exec.Command("git", "remote", "get-url", "origin") + cmd.Dir = tmpDir + out, err := cmd.Output() + if err != nil { + t.Fatalf("get-url failed: %v", err) + } + + url := string(out) + if url != "https://github.com/org/repo.git\n" { + t.Errorf("expected stripped URL, got %q", url) + } +} + +func TestGitOps_ConfigureUser(t *testing.T) { + tmpDir := t.TempDir() + + cmd := exec.Command("git", "init") + cmd.Dir = tmpDir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git init failed: %v\n%s", err, string(out)) + } + + logger := zap.NewNop() + gitOps := NewGitOps(exec.Command, logger) + + if err := gitOps.ConfigureUser(tmpDir, "test-bot", "bot@test.com"); err != nil { + t.Fatalf("ConfigureUser failed: %v", err) + } + + // Verify. + nameCmd := exec.Command("git", "config", "user.name") + nameCmd.Dir = tmpDir + nameOut, _ := nameCmd.Output() + if string(nameOut) != "test-bot\n" { + t.Errorf("expected user.name=test-bot, got %q", string(nameOut)) + } + + emailCmd := exec.Command("git", "config", "user.email") + emailCmd.Dir = tmpDir + emailOut, _ := emailCmd.Output() + if string(emailOut) != "bot@test.com\n" { + t.Errorf("expected user.email=bot@test.com, got %q", string(emailOut)) + } +} + +func TestGitOps_ConfigureSSHSigning_NoKey(t *testing.T) { + tmpDir := t.TempDir() + + cmd := exec.Command("git", "init") + cmd.Dir = tmpDir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git init failed: %v\n%s", err, string(out)) + } + + logger := zap.NewNop() + gitOps := NewGitOps(exec.Command, logger) + + // Empty path should be a no-op. + if err := gitOps.ConfigureSSHSigning(tmpDir, ""); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + // Non-existent path should be a no-op (returns nil). + if err := gitOps.ConfigureSSHSigning(tmpDir, "/nonexistent/key"); err != nil { + t.Fatalf("unexpected error for nonexistent key: %v", err) + } +} + +func TestGitOps_CloneImport(t *testing.T) { + // Create a bare repo to clone from. + bareDir := t.TempDir() + cmd := exec.Command("git", "init", "--bare") + cmd.Dir = bareDir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git init --bare failed: %v\n%s", err, string(out)) + } + + destDir := filepath.Join(t.TempDir(), "clone") + + logger := zap.NewNop() + gitOps := NewGitOps(exec.Command, logger) + + if err := gitOps.CloneImport(bareDir, destDir, ""); err != nil { + t.Fatalf("CloneImport failed: %v", err) + } + + // Verify .git directory exists in destination. + if _, err := os.Stat(filepath.Join(destDir, ".git")); err != nil { + t.Errorf("expected .git directory in clone, got error: %v", err) + } +} diff --git a/services/hosting/router.go b/services/hosting/router.go new file mode 100644 index 0000000..2626ff1 --- /dev/null +++ b/services/hosting/router.go @@ -0,0 +1,302 @@ +// Package hosting provides a multi-provider router that satisfies all +// consumer-defined interfaces (executor.GitService, scanner.PRFetcher, +// scanner.PRLabeler, scanner.CIChecker, scanner.MergeabilityChecker, +// workspace.Cloner, recovery.GitService) by dispatching method calls +// to the correct VCS backend based on owner/repo. +// +// The router holds a mapping of owner/repo → provider built from the +// application config at startup. Methods that receive only a local +// directory path (CreateBranch, SwitchBranch, etc.) use a workspace +// registry populated during clone operations to resolve the provider. +package hosting + +import ( + "fmt" + "strings" + "sync" + "time" + + "jira-ai-issue-solver/models" +) + +// Provider defines the union of all methods needed by any consumer in +// the application. Both GitHubServiceImpl and GitLabServiceImpl satisfy +// this interface. +type Provider interface { + // workspace.Cloner + CloneRepository(repoURL, directory string) error + + // executor.GitService + SyncFork(forkOwner, repo, branch string) error + CreateBranch(dir, name, baseBranch string) error + SwitchBranch(dir, name string) error + RemoteBranchExists(owner, repo, branch string) (bool, error) + DeleteRemoteBranch(owner, repo, branch string) error + HasChanges(dir, baseBranch string) (bool, error) + CommitChanges(upstreamOwner, owner, repo, branch, message, dir, baseBranch string, + coAuthor *models.Author, importExcludes []string, skipFileGuardrail ...bool) (string, error) + StripRemoteAuth(dir string) error + RestoreRemoteAuth(dir, owner, repo string) error + FetchRemote(dir string) error + SyncWithRemote(dir, branch string, importExcludes []string) error + CreatePR(params models.PRParams) (*models.PR, error) + GetPRForBranch(owner, repo, head string) (*models.PRDetails, error) + GetPRComments(owner, repo string, number int, since time.Time) ([]models.PRComment, error) + ReplyToComment(owner, repo string, prNumber int, commentID int64, body string) error + PostIssueComment(owner, repo string, prNumber int, body string) error + ListIssueComments(owner, repo string, prNumber int) ([]models.IssueComment, error) + UpdateIssueComment(owner, repo string, commentID int64, body string) error + AddCommentReaction(owner, repo string, comment models.PRComment, reaction string) error + MergeBase(dir, branch, fetchURL string) ([]string, error) + CloneImport(url, destDir, ref string) error + ListCheckRunsForRef(owner, repo, ref string) ([]models.CheckRunFailure, bool, error) + ListCheckRunAnnotations(owner, repo string, checkRunID int64) ([]models.CheckAnnotation, error) + GetFailedJobLogs(owner, repo, headSHA string, maxBytesPerStep int) (map[string][]models.FailedStep, error) + AddPRLabel(owner, repo string, number int, label string) error + RemovePRLabel(owner, repo string, number int, label string) error + + // scanner.PRFetcher (additional methods beyond executor.GitService) + GetClosedPRForBranch(owner, repo, head string) (*models.PRDetails, error) + GetMergedPRForBranch(owner, repo, head string) (*models.PRDetails, error) + + // scanner.PRLabeler (additional methods beyond executor.GitService) + HasPRLabel(owner, repo string, number int, label string) (bool, error) + LastLabelRemoval(owner, repo string, number int, label string) (time.Time, error) + + // scanner.MergeabilityChecker + GetPRMergeability(owner, repo string, number int) (*models.PRMergeState, error) + + // recovery.GitService + BranchHasCommits(owner, repo, branch, base string) (bool, error) +} + +// Router dispatches method calls to the correct VCS backend based on +// owner/repo. For methods that receive only a directory path, it uses +// a workspace registry populated during CloneRepository calls. +type Router struct { + // repoProviders maps "owner/repo" → Provider. + repoProviders map[string]Provider + + // workspaceDirs maps directory path → Provider, populated on + // CloneRepository so dir-based methods can resolve the provider. + workspaceDirs map[string]Provider + workspaceDirsMu sync.RWMutex + + // fallback is used when no explicit mapping exists. + fallback Provider +} + +// NewRouter creates a Router from a repo→provider mapping. The fallback +// provider is used for repos not in the map (backward compatibility: +// pass the GitHub service as fallback). +func NewRouter(repoProviders map[string]Provider, fallback Provider) *Router { + normalized := make(map[string]Provider, len(repoProviders)) + for key, provider := range repoProviders { + normalized[strings.ToLower(key)] = provider + } + return &Router{ + repoProviders: normalized, + workspaceDirs: make(map[string]Provider), + fallback: fallback, + } +} + +// RegisterWorkspace associates a directory path with a provider so +// dir-based methods can dispatch correctly. +func (r *Router) RegisterWorkspace(dir string, owner, repo string) { + r.workspaceDirsMu.Lock() + defer r.workspaceDirsMu.Unlock() + r.workspaceDirs[dir] = r.forRepo(owner, repo) +} + +func (r *Router) forRepo(owner, repo string) Provider { + key := strings.ToLower(owner + "/" + repo) + if p, ok := r.repoProviders[key]; ok { + return p + } + return r.fallback +} + +func (r *Router) forDir(dir string) Provider { + r.workspaceDirsMu.RLock() + defer r.workspaceDirsMu.RUnlock() + if p, ok := r.workspaceDirs[dir]; ok { + return p + } + return r.fallback +} + +// --- workspace.Cloner --- + +func (r *Router) CloneRepository(repoURL, directory string) error { + owner, repo := extractOwnerRepo(repoURL) + p := r.forRepo(owner, repo) + err := p.CloneRepository(repoURL, directory) + if err == nil { + r.workspaceDirsMu.Lock() + r.workspaceDirs[directory] = p + r.workspaceDirsMu.Unlock() + } + return err +} + +// --- Dir-based methods (use workspace registry) --- + +func (r *Router) CreateBranch(dir, name, baseBranch string) error { + return r.forDir(dir).CreateBranch(dir, name, baseBranch) +} + +func (r *Router) SwitchBranch(dir, name string) error { + return r.forDir(dir).SwitchBranch(dir, name) +} + +func (r *Router) HasChanges(dir, baseBranch string) (bool, error) { + return r.forDir(dir).HasChanges(dir, baseBranch) +} + +func (r *Router) StripRemoteAuth(dir string) error { + return r.forDir(dir).StripRemoteAuth(dir) +} + +func (r *Router) FetchRemote(dir string) error { + return r.forDir(dir).FetchRemote(dir) +} + +func (r *Router) SyncWithRemote(dir, branch string, importExcludes []string) error { + return r.forDir(dir).SyncWithRemote(dir, branch, importExcludes) +} + +func (r *Router) MergeBase(dir, branch, fetchURL string) ([]string, error) { + return r.forDir(dir).MergeBase(dir, branch, fetchURL) +} + +func (r *Router) CloneImport(url, destDir, ref string) error { + return r.forDir(destDir).CloneImport(url, destDir, ref) +} + +// --- Owner/repo-based methods (use repo registry) --- + +func (r *Router) SyncFork(forkOwner, repo, branch string) error { + return r.forRepo(forkOwner, repo).SyncFork(forkOwner, repo, branch) +} + +func (r *Router) RemoteBranchExists(owner, repo, branch string) (bool, error) { + return r.forRepo(owner, repo).RemoteBranchExists(owner, repo, branch) +} + +func (r *Router) DeleteRemoteBranch(owner, repo, branch string) error { + return r.forRepo(owner, repo).DeleteRemoteBranch(owner, repo, branch) +} + +func (r *Router) CommitChanges(upstreamOwner, owner, repo, branch, message, dir, baseBranch string, + coAuthor *models.Author, importExcludes []string, skipFileGuardrail ...bool) (string, error) { + return r.forRepo(owner, repo).CommitChanges(upstreamOwner, owner, repo, branch, message, dir, baseBranch, coAuthor, importExcludes, skipFileGuardrail...) +} + +func (r *Router) RestoreRemoteAuth(dir, owner, repo string) error { + return r.forRepo(owner, repo).RestoreRemoteAuth(dir, owner, repo) +} + +func (r *Router) CreatePR(params models.PRParams) (*models.PR, error) { + return r.forRepo(params.Owner, params.Repo).CreatePR(params) +} + +func (r *Router) GetPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + return r.forRepo(owner, repo).GetPRForBranch(owner, repo, head) +} + +func (r *Router) GetClosedPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + return r.forRepo(owner, repo).GetClosedPRForBranch(owner, repo, head) +} + +func (r *Router) GetMergedPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + return r.forRepo(owner, repo).GetMergedPRForBranch(owner, repo, head) +} + +func (r *Router) GetPRComments(owner, repo string, number int, since time.Time) ([]models.PRComment, error) { + return r.forRepo(owner, repo).GetPRComments(owner, repo, number, since) +} + +func (r *Router) ReplyToComment(owner, repo string, prNumber int, commentID int64, body string) error { + return r.forRepo(owner, repo).ReplyToComment(owner, repo, prNumber, commentID, body) +} + +func (r *Router) PostIssueComment(owner, repo string, prNumber int, body string) error { + return r.forRepo(owner, repo).PostIssueComment(owner, repo, prNumber, body) +} + +func (r *Router) ListIssueComments(owner, repo string, prNumber int) ([]models.IssueComment, error) { + return r.forRepo(owner, repo).ListIssueComments(owner, repo, prNumber) +} + +func (r *Router) UpdateIssueComment(owner, repo string, commentID int64, body string) error { + // commentID-based calls don't have owner/repo; fallback for now. + return r.fallback.UpdateIssueComment(owner, repo, commentID, body) +} + +func (r *Router) AddCommentReaction(owner, repo string, comment models.PRComment, reaction string) error { + return r.forRepo(owner, repo).AddCommentReaction(owner, repo, comment, reaction) +} + +func (r *Router) ListCheckRunsForRef(owner, repo, ref string) ([]models.CheckRunFailure, bool, error) { + return r.forRepo(owner, repo).ListCheckRunsForRef(owner, repo, ref) +} + +func (r *Router) ListCheckRunAnnotations(owner, repo string, checkRunID int64) ([]models.CheckAnnotation, error) { + return r.forRepo(owner, repo).ListCheckRunAnnotations(owner, repo, checkRunID) +} + +func (r *Router) GetFailedJobLogs(owner, repo, headSHA string, maxBytesPerStep int) (map[string][]models.FailedStep, error) { + return r.forRepo(owner, repo).GetFailedJobLogs(owner, repo, headSHA, maxBytesPerStep) +} + +func (r *Router) AddPRLabel(owner, repo string, number int, label string) error { + return r.forRepo(owner, repo).AddPRLabel(owner, repo, number, label) +} + +func (r *Router) RemovePRLabel(owner, repo string, number int, label string) error { + return r.forRepo(owner, repo).RemovePRLabel(owner, repo, number, label) +} + +func (r *Router) HasPRLabel(owner, repo string, number int, label string) (bool, error) { + return r.forRepo(owner, repo).HasPRLabel(owner, repo, number, label) +} + +func (r *Router) LastLabelRemoval(owner, repo string, number int, label string) (time.Time, error) { + return r.forRepo(owner, repo).LastLabelRemoval(owner, repo, number, label) +} + +func (r *Router) GetPRMergeability(owner, repo string, number int) (*models.PRMergeState, error) { + return r.forRepo(owner, repo).GetPRMergeability(owner, repo, number) +} + +func (r *Router) BranchHasCommits(owner, repo, branch, base string) (bool, error) { + return r.forRepo(owner, repo).BranchHasCommits(owner, repo, branch, base) +} + +// extractOwnerRepo parses a clone URL into owner and repo. +// Handles https://host/owner/repo.git and git@host:owner/repo.git formats. +func extractOwnerRepo(repoURL string) (string, string) { + repoURL = strings.TrimSuffix(repoURL, ".git") + + // SSH format: git@host:owner/repo + if strings.Contains(repoURL, ":") && !strings.Contains(repoURL, "://") { + parts := strings.SplitN(repoURL, ":", 2) + if len(parts) == 2 { + pathParts := strings.Split(parts[1], "/") + if len(pathParts) >= 2 { + return strings.Join(pathParts[:len(pathParts)-1], "/"), pathParts[len(pathParts)-1] + } + } + } + + // HTTPS format: https://host/owner/[subgroups/]repo + parts := strings.Split(repoURL, "/") + if len(parts) >= 5 { + repo := parts[len(parts)-1] + owner := strings.Join(parts[3:len(parts)-1], "/") + return owner, repo + } + + return "", fmt.Sprintf("unknown-%s", repoURL) +} diff --git a/services/hosting/router_test.go b/services/hosting/router_test.go new file mode 100644 index 0000000..a0635f3 --- /dev/null +++ b/services/hosting/router_test.go @@ -0,0 +1,282 @@ +package hosting + +import ( + "testing" + "time" + + "jira-ai-issue-solver/models" +) + +// stubProvider is a minimal test double for the Provider interface. +type stubProvider struct { + name string + // Track which methods were called. + calls []string +} + +func (p *stubProvider) CloneRepository(repoURL, directory string) error { + p.calls = append(p.calls, "CloneRepository") + return nil +} +func (p *stubProvider) SyncFork(forkOwner, repo, branch string) error { + p.calls = append(p.calls, "SyncFork") + return nil +} +func (p *stubProvider) CreateBranch(dir, name, baseBranch string) error { + p.calls = append(p.calls, "CreateBranch") + return nil +} +func (p *stubProvider) SwitchBranch(dir, name string) error { + p.calls = append(p.calls, "SwitchBranch") + return nil +} +func (p *stubProvider) RemoteBranchExists(owner, repo, branch string) (bool, error) { + p.calls = append(p.calls, "RemoteBranchExists") + return false, nil +} +func (p *stubProvider) DeleteRemoteBranch(owner, repo, branch string) error { + p.calls = append(p.calls, "DeleteRemoteBranch") + return nil +} +func (p *stubProvider) HasChanges(dir, baseBranch string) (bool, error) { + p.calls = append(p.calls, "HasChanges") + return false, nil +} +func (p *stubProvider) CommitChanges(upstreamOwner, owner, repo, branch, message, dir, baseBranch string, coAuthor *models.Author, importExcludes []string, skipFileGuardrail ...bool) (string, error) { + p.calls = append(p.calls, "CommitChanges") + return "sha123", nil +} +func (p *stubProvider) StripRemoteAuth(dir string) error { + p.calls = append(p.calls, "StripRemoteAuth") + return nil +} +func (p *stubProvider) RestoreRemoteAuth(dir, owner, repo string) error { + p.calls = append(p.calls, "RestoreRemoteAuth") + return nil +} +func (p *stubProvider) FetchRemote(dir string) error { + p.calls = append(p.calls, "FetchRemote") + return nil +} +func (p *stubProvider) SyncWithRemote(dir, branch string, importExcludes []string) error { + p.calls = append(p.calls, "SyncWithRemote") + return nil +} +func (p *stubProvider) CreatePR(params models.PRParams) (*models.PR, error) { + p.calls = append(p.calls, "CreatePR") + return &models.PR{Number: 1}, nil +} +func (p *stubProvider) GetPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + p.calls = append(p.calls, "GetPRForBranch") + return nil, nil +} +func (p *stubProvider) GetPRComments(owner, repo string, number int, since time.Time) ([]models.PRComment, error) { + p.calls = append(p.calls, "GetPRComments") + return []models.PRComment{}, nil +} +func (p *stubProvider) ReplyToComment(owner, repo string, prNumber int, commentID int64, body string) error { + p.calls = append(p.calls, "ReplyToComment") + return nil +} +func (p *stubProvider) PostIssueComment(owner, repo string, prNumber int, body string) error { + p.calls = append(p.calls, "PostIssueComment") + return nil +} +func (p *stubProvider) ListIssueComments(owner, repo string, prNumber int) ([]models.IssueComment, error) { + p.calls = append(p.calls, "ListIssueComments") + return []models.IssueComment{}, nil +} +func (p *stubProvider) UpdateIssueComment(owner, repo string, commentID int64, body string) error { + p.calls = append(p.calls, "UpdateIssueComment") + return nil +} +func (p *stubProvider) AddCommentReaction(owner, repo string, comment models.PRComment, reaction string) error { + p.calls = append(p.calls, "AddCommentReaction") + return nil +} +func (p *stubProvider) MergeBase(dir, branch, fetchURL string) ([]string, error) { + p.calls = append(p.calls, "MergeBase") + return []string{}, nil +} +func (p *stubProvider) CloneImport(url, destDir, ref string) error { + p.calls = append(p.calls, "CloneImport") + return nil +} +func (p *stubProvider) ListCheckRunsForRef(owner, repo, ref string) ([]models.CheckRunFailure, bool, error) { + p.calls = append(p.calls, "ListCheckRunsForRef") + return []models.CheckRunFailure{}, true, nil +} +func (p *stubProvider) ListCheckRunAnnotations(owner, repo string, checkRunID int64) ([]models.CheckAnnotation, error) { + p.calls = append(p.calls, "ListCheckRunAnnotations") + return []models.CheckAnnotation{}, nil +} +func (p *stubProvider) GetFailedJobLogs(owner, repo, headSHA string, maxBytesPerStep int) (map[string][]models.FailedStep, error) { + p.calls = append(p.calls, "GetFailedJobLogs") + return map[string][]models.FailedStep{}, nil +} +func (p *stubProvider) AddPRLabel(owner, repo string, number int, label string) error { + p.calls = append(p.calls, "AddPRLabel") + return nil +} +func (p *stubProvider) RemovePRLabel(owner, repo string, number int, label string) error { + p.calls = append(p.calls, "RemovePRLabel") + return nil +} +func (p *stubProvider) GetClosedPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + p.calls = append(p.calls, "GetClosedPRForBranch") + return nil, nil +} +func (p *stubProvider) GetMergedPRForBranch(owner, repo, head string) (*models.PRDetails, error) { + p.calls = append(p.calls, "GetMergedPRForBranch") + return nil, nil +} +func (p *stubProvider) HasPRLabel(owner, repo string, number int, label string) (bool, error) { + p.calls = append(p.calls, "HasPRLabel") + return false, nil +} +func (p *stubProvider) LastLabelRemoval(owner, repo string, number int, label string) (time.Time, error) { + p.calls = append(p.calls, "LastLabelRemoval") + return time.Time{}, nil +} +func (p *stubProvider) GetPRMergeability(owner, repo string, number int) (*models.PRMergeState, error) { + p.calls = append(p.calls, "GetPRMergeability") + return nil, nil +} +func (p *stubProvider) BranchHasCommits(owner, repo, branch, base string) (bool, error) { + p.calls = append(p.calls, "BranchHasCommits") + return false, nil +} + +func TestRouter_RoutesToCorrectProvider(t *testing.T) { + github := &stubProvider{name: "github"} + gitlab := &stubProvider{name: "gitlab"} + + repoProviders := map[string]Provider{ + "gitlab-org/repo": gitlab, + "github-org/repo": github, + } + + router := NewRouter(repoProviders, github) + + // API-based call should route to gitlab for gitlab-org/repo. + router.GetPRForBranch("gitlab-org", "repo", "feature") + if len(gitlab.calls) != 1 || gitlab.calls[0] != "GetPRForBranch" { + t.Errorf("expected gitlab to receive GetPRForBranch, got %v", gitlab.calls) + } + if len(github.calls) != 0 { + t.Errorf("expected github to receive no calls, got %v", github.calls) + } + + // API-based call should route to github for github-org/repo. + router.GetPRForBranch("github-org", "repo", "feature") + if len(github.calls) != 1 || github.calls[0] != "GetPRForBranch" { + t.Errorf("expected github to receive GetPRForBranch, got %v", github.calls) + } +} + +func TestRouter_FallbackToDefault(t *testing.T) { + github := &stubProvider{name: "github"} + gitlab := &stubProvider{name: "gitlab"} + + repoProviders := map[string]Provider{ + "gitlab-org/repo": gitlab, + } + + router := NewRouter(repoProviders, github) + + // Unknown repo should fall back to the default (github). + router.GetPRForBranch("unknown-org", "unknown-repo", "feature") + if len(github.calls) != 1 || github.calls[0] != "GetPRForBranch" { + t.Errorf("expected github (fallback) to receive call, got %v", github.calls) + } +} + +func TestRouter_DirBasedMethodsUseWorkspaceRegistry(t *testing.T) { + github := &stubProvider{name: "github"} + gitlab := &stubProvider{name: "gitlab"} + + repoProviders := map[string]Provider{ + "gitlab-org/repo": gitlab, + } + + router := NewRouter(repoProviders, github) + + // Register a workspace directory with the gitlab provider. + router.RegisterWorkspace("/tmp/workspaces/ticket-1/repo", "gitlab-org", "repo") + + // Dir-based call should route to gitlab. + router.CreateBranch("/tmp/workspaces/ticket-1/repo", "feature", "main") + if len(gitlab.calls) != 1 || gitlab.calls[0] != "CreateBranch" { + t.Errorf("expected gitlab to receive CreateBranch, got %v", gitlab.calls) + } + + // Unknown dir should fall back. + router.CreateBranch("/tmp/workspaces/ticket-2/repo", "feature", "main") + if len(github.calls) != 1 || github.calls[0] != "CreateBranch" { + t.Errorf("expected github (fallback) for unknown dir, got %v", github.calls) + } +} + +func TestRouter_CloneRegistersWorkspace(t *testing.T) { + github := &stubProvider{name: "github"} + gitlab := &stubProvider{name: "gitlab"} + + repoProviders := map[string]Provider{ + "gitlab-org/repo": gitlab, + } + + router := NewRouter(repoProviders, github) + + // Clone registers the workspace directory. + router.CloneRepository("https://gitlab.com/gitlab-org/repo.git", "/tmp/workspaces/ws1") + + if len(gitlab.calls) != 1 || gitlab.calls[0] != "CloneRepository" { + t.Errorf("expected gitlab to receive CloneRepository, got %v", gitlab.calls) + } + + // Subsequent dir-based call should route to gitlab. + router.HasChanges("/tmp/workspaces/ws1", "main") + if len(gitlab.calls) != 2 || gitlab.calls[1] != "HasChanges" { + t.Errorf("expected gitlab to receive HasChanges after clone, got %v", gitlab.calls) + } +} + +func TestRouter_CaseInsensitiveRouting(t *testing.T) { + github := &stubProvider{name: "github"} + gitlab := &stubProvider{name: "gitlab"} + + repoProviders := map[string]Provider{ + "GitLab-Org/Repo": gitlab, + } + + router := NewRouter(repoProviders, github) + + // Lowercase lookup should still find the provider. + router.GetPRForBranch("gitlab-org", "repo", "feature") + if len(gitlab.calls) != 1 { + t.Errorf("expected case-insensitive match to gitlab, got %v", gitlab.calls) + } +} + +func TestExtractOwnerRepo(t *testing.T) { + tests := []struct { + url string + wantOwner string + wantRepo string + }{ + {"https://github.com/org/repo.git", "org", "repo"}, + {"https://gitlab.com/group/subgroup/repo.git", "group/subgroup", "repo"}, + {"git@github.com:org/repo.git", "org", "repo"}, + {"https://gitlab.cee.redhat.com/a/b/c.git", "a/b", "c"}, + } + + for _, tt := range tests { + owner, repo := extractOwnerRepo(tt.url) + if owner != tt.wantOwner { + t.Errorf("extractOwnerRepo(%s): owner=%q, want %q", tt.url, owner, tt.wantOwner) + } + if repo != tt.wantRepo { + t.Errorf("extractOwnerRepo(%s): repo=%q, want %q", tt.url, repo, tt.wantRepo) + } + } +}