diff --git a/CLAUDE.md b/CLAUDE.md index 4f5b59f..ed8da5b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,6 @@ # CLAUDE.md — reviewd -Local AI code review daemon for GitHub/BitBucket PRs. See README.md for full docs. +Local AI code review daemon for GitHub/GitLab/BitBucket PRs. See README.md for full docs. ## Project Conventions @@ -28,6 +28,7 @@ Local AI code review daemon for GitHub/BitBucket PRs. See README.md for full doc | `src/reviewd/providers/base.py` | Abstract GitProvider ABC | | `src/reviewd/providers/bitbucket.py` | BitBucket 2.0 API (httpx, pagination with ID dedup, inline comments) | | `src/reviewd/providers/github.py` | GitHub REST API v3 (httpx, Link header pagination, review comments) | +| `src/reviewd/providers/gitlab.py` | GitLab REST API v4 (httpx, self-hosted `url`, MR notes + diff discussions) | ## Releasing @@ -50,6 +51,7 @@ rm -rf dist && uv build && uv publish - Claude CLI rejects nested sessions — must unset `CLAUDECODE` env var in subprocess - Gemini CLI loads global extensions by default — use `-e none` to disable - Codex CLI outputs raw JSON (no markdown fences) — extract_json falls back to raw JSON object parsing +- GitLab inline comments anchor only on lines shown in the MR diff; findings on other lines (or in files GitLab collapsed) become file-level comments that name the line. `critical_task` is BitBucket-only - Inline suggestions are single-line only (TODO: multi-line support) - AI may hallucinate line numbers — prompt instructs to double-check but not guaranteed - `cli: claude_interactive` drives an *interactive* Claude session over a pexpect PTY (no `--print`, no tmux), to bill against the subscription instead of API credits. The prompt tells Claude to write the review JSON to a temp file via `Write` + atomic `mv`; reviewd waits for that file (watching the PTY stream for usage/login errors + an overall timeout). Requires `claude` logged in via `/login`; if `ANTHROPIC_API_KEY` is exported it may still be used. Runs with `--dangerously-skip-permissions` so Write/Bash run unattended in the worktree. diff --git a/README.md b/README.md index 10309f1..68ed768 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![CI](https://github.com/simion/reviewd/actions/workflows/ci.yml/badge.svg)](https://github.com/simion/reviewd/actions/workflows/ci.yml) -**Your local code review assistant** — review GitHub and BitBucket pull requests from your terminal, powered by Claude Code / Gemini / Codex CLI. +**Your local code review assistant** — review GitHub, GitLab and BitBucket pull requests from your terminal, powered by Claude Code / Gemini / Codex CLI. https://github.com/user-attachments/assets/e99705d6-5595-478e-b5de-f47d3abcfa37 @@ -67,7 +67,7 @@ Requires Python 3.12+. You also need `claude`, `gemini`, or `codex` CLI installe reviewd init # interactive wizard — detects repos, guides token creation, writes config ``` -The wizard scans your repos, detects GitHub/BitBucket remotes, validates credentials, and writes both global and per-project configs. Prefer YAML? Choose "Sample config file" to get an annotated template instead. +The wizard scans your repos, detects GitHub/GitLab/BitBucket remotes, validates credentials, and writes both global and per-project configs. Prefer YAML? Choose "Sample config file" to get an annotated template instead.
GitHub setup @@ -124,7 +124,29 @@ repos:
-Both providers can be used in the same config. Tokens support `${ENV_VAR}` substitution. +
+GitLab setup + +1. Create a [Personal Access Token](https://gitlab.com/-/user_settings/personal_access_tokens) (or a project/group access token) with the **api** scope. +2. Config: + +```yaml +gitlab: + token: glpat-YOUR_TOKEN + # url: https://gitlab.example.com # self-hosted instance (default: https://gitlab.com) + +repos: + - name: my-repo + repo_slug: group/subgroup/my-repo # full project path + path: ~/repos/my-repo + provider: gitlab +``` + +A repo on a different GitLab instance can set its own `gitlab:` block (`token` + `url`) to override the global one. + +
+ +GitHub, GitLab and BitBucket repos can be mixed in the same config. Tokens support `${ENV_VAR}` substitution. ### 3. Review @@ -140,7 +162,7 @@ reviewd watch -v # continuous review loop Check API -> State Check (SQLite) -> Fetch & Worktree -> AI Review (Claude/Gemini/Codex) -> Parse JSON -> Post Comments -> Cleanup ``` -1. Fetches open PRs from GitHub/BitBucket +1. Fetches open PRs from GitHub/GitLab/BitBucket 2. Skips already-reviewed commits, drafts, cooldowns, and small diffs 3. Creates a git worktree, runs configured test commands 4. Invokes the AI CLI with a structured prompt and JSON output schema @@ -157,6 +179,10 @@ max_concurrent_reviews: 4 github: token: ${GITHUB_TOKEN} +gitlab: + token: ${GITLAB_TOKEN} + # url: https://gitlab.example.com + bitbucket: your-workspace: you@example.com:${BB_API_TOKEN} other-workspace: other@example.com:${OTHER_BB_TOKEN} @@ -185,6 +211,11 @@ repos: workspace: your-workspace cli: gemini # or "codex" model: gemini-2.5-pro + + - name: gl-service + repo_slug: group/gl-service + path: ~/repos/gl-service + provider: gitlab ``` ### Per-project (`.reviewd.yaml` in repo root) @@ -283,7 +314,7 @@ reviewd status # review history - **Full AI tool access** — the AI reads files, runs commands, explores code in the worktree - **JSON schema** — structured findings, the tool just parses and posts - **SQLite state** — WAL mode, thread-safe, tracks `(repo, pr_id, commit)` to avoid duplicates -- **Provider abstraction** — GitHub and BitBucket, extensible +- **Provider abstraction** — GitHub, GitLab and BitBucket, extensible ## Security diff --git a/pyproject.toml b/pyproject.toml index 9abf265..89a0e87 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,12 +1,12 @@ [project] name = "reviewd" version = "0.7.2" -description = "Local AI code reviewer for GitHub and BitBucket PRs — uses Claude, Gemini, or Codex CLI to review pull requests and post structured comments" +description = "Local AI code reviewer for GitHub, GitLab and BitBucket PRs — uses Claude, Gemini, or Codex CLI to review pull requests and post structured comments" readme = "README.md" license = "MIT" requires-python = ">=3.12" authors = [{name = "Simion Agavriloaei", email = "hi@simion.cv"}] -keywords = ["code-review", "ai", "github", "bitbucket", "pull-request", "claude", "gemini", "codex", "automation"] +keywords = ["code-review", "ai", "github", "gitlab", "bitbucket", "pull-request", "claude", "gemini", "codex", "automation"] classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", diff --git a/src/reviewd/config.example.yaml b/src/reviewd/config.example.yaml index f024ce5..a936890 100644 --- a/src/reviewd/config.example.yaml +++ b/src/reviewd/config.example.yaml @@ -4,7 +4,7 @@ # Run `reviewd init` to copy this file to the right location. # Uncomment and customize the settings you need. -# --- Provider credentials (configure one or both) --- +# --- Provider credentials (configure the ones you need) --- # GitHub (requires a Personal Access Token with `repo` scope) # github: @@ -30,6 +30,14 @@ # my-workspace: ${BB_WORKSPACE_TOKEN} # workspace token (Bearer) # # or: my-workspace: ${BB_EMAIL}:${BB_USER_TOKEN} # user token (Basic) +# GitLab (Personal/Project/Group Access Token with `api` scope) +# Create at: https://gitlab.com/-/user_settings/personal_access_tokens +# url defaults to https://gitlab.com — set it for self-hosted instances. +# A repo can override this with its own `gitlab:` block (token + url). +# gitlab: +# token: ${GITLAB_TOKEN} +# # url: https://gitlab.example.com + # --- AI CLI settings --- # AI CLI to use: "claude" or "gemini" (default: claude) @@ -141,6 +149,11 @@ repos: [] # path: ~/repos/my-bb-project # provider: bitbucket # workspace: my-workspace # must match a key in bitbucket section + # + # - name: my-gl-project + # repo_slug: group/subgroup/my-gl-project # full project path for GitLab API + # path: ~/repos/my-gl-project + # provider: gitlab # # cli: gemini # override per repo # # model: gemini-2.5-pro # override per repo diff --git a/src/reviewd/config.py b/src/reviewd/config.py index b7e5ae9..0493d37 100644 --- a/src/reviewd/config.py +++ b/src/reviewd/config.py @@ -13,6 +13,7 @@ SEVERITY_ORDER, AutoApproveConfig, GithubConfig, + GitlabConfig, GlobalConfig, ProjectConfig, RepoConfig, @@ -43,6 +44,13 @@ def _parse_github_config(data: dict) -> GithubConfig: ) +def _parse_gitlab_config(data: dict) -> GitlabConfig: + return GitlabConfig( + token=_resolve_env_vars(str(data['token'])), + url=_resolve_env_vars(str(data.get('url', GitlabConfig.url))), + ) + + def _parse_cli(value: str, repo_name: str | None = None) -> CLI: value = str(value).strip() if ' ' in value: @@ -148,6 +156,8 @@ def load_global_config(path: str | Path | None = None) -> GlobalConfig: if 'github' in data: global_gh = _parse_github_config(data['github']) + global_gl = _parse_gitlab_config(data['gitlab']) if 'gitlab' in data else None + global_cli = _parse_cli(data.get('cli', 'claude')) repos = [] @@ -159,6 +169,7 @@ def load_global_config(path: str | Path | None = None) -> GlobalConfig: repo_gh = None if 'github' in repo_data: repo_gh = _parse_github_config(repo_data['github']) + repo_gl = _parse_gitlab_config(repo_data['gitlab']) if 'gitlab' in repo_data else None repo_cli = _parse_cli(repo_data['cli'], repo_data['name']) if 'cli' in repo_data else global_cli repos.append( @@ -169,6 +180,7 @@ def load_global_config(path: str | Path | None = None) -> GlobalConfig: repo_slug=repo_data.get('repo_slug'), workspace=repo_data.get('workspace'), github=repo_gh, + gitlab=repo_gl, cli=repo_cli, model=repo_data.get('model', data.get('model')), ) @@ -184,6 +196,7 @@ def load_global_config(path: str | Path | None = None) -> GlobalConfig: repos=repos, bitbucket=global_bb, github=global_gh, + gitlab=global_gl, state_db=state_db, cli=global_cli, model=data.get('model'), @@ -317,6 +330,14 @@ def resolve_github_config(global_config: GlobalConfig, repo_config: RepoConfig) raise ValueError(f'No github config found for repo "{repo_config.name}"') +def resolve_gitlab_config(global_config: GlobalConfig, repo_config: RepoConfig) -> GitlabConfig: + if repo_config.gitlab is not None: + return repo_config.gitlab + if global_config.gitlab is not None: + return global_config.gitlab + raise ValueError(f'No gitlab config found for repo "{repo_config.name}"') + + def get_provider(global_config: GlobalConfig, repo_config: RepoConfig) -> GitProvider: if repo_config.provider == 'github': from reviewd.providers.github import GithubProvider @@ -324,6 +345,11 @@ def get_provider(global_config: GlobalConfig, repo_config: RepoConfig) -> GitPro config = resolve_github_config(global_config, repo_config) return GithubProvider(config) + if repo_config.provider == 'gitlab': + from reviewd.providers.gitlab import GitlabProvider + + return GitlabProvider(resolve_gitlab_config(global_config, repo_config)) + from reviewd.providers.bitbucket import BitbucketProvider workspace, token = resolve_bitbucket_config(global_config, repo_config) diff --git a/src/reviewd/models.py b/src/reviewd/models.py index aad3f38..28bf995 100644 --- a/src/reviewd/models.py +++ b/src/reviewd/models.py @@ -60,6 +60,12 @@ class GithubConfig: token: str +@dataclass +class GitlabConfig: + token: str + url: str = 'https://gitlab.com' + + @dataclass class AutoApproveConfig: enabled: bool = False @@ -101,6 +107,7 @@ class RepoConfig: repo_slug: str | None = None workspace: str | None = None github: GithubConfig | None = None + gitlab: GitlabConfig | None = None cli: CLI = CLI.CLAUDE model: str | None = None @@ -114,6 +121,7 @@ class GlobalConfig: repos: list[RepoConfig] bitbucket: dict[str, str] = field(default_factory=dict) github: GithubConfig | None = None + gitlab: GitlabConfig | None = None state_db: str = '' cli: CLI = CLI.CLAUDE model: str | None = None diff --git a/src/reviewd/providers/base.py b/src/reviewd/providers/base.py index e10645b..da1d37f 100644 --- a/src/reviewd/providers/base.py +++ b/src/reviewd/providers/base.py @@ -1,11 +1,51 @@ from __future__ import annotations +import logging +import time from abc import ABC, abstractmethod +import httpx + from reviewd.models import PRInfo +logger = logging.getLogger(__name__) + + +def parse_next_link(link_header: str) -> str | None: + for part in link_header.split(','): + if 'rel="next"' in part: + url = part.split(';')[0].strip().strip('<>') + return url + return None + class GitProvider(ABC): + client: httpx.Client + + def _request(self, method: str, url: str, **kwargs) -> httpx.Response: + max_retries = 3 + for attempt in range(max_retries + 1): + resp = self.client.request(method, url, **kwargs) + if resp.status_code != 429 or attempt == max_retries: + resp.raise_for_status() + return resp + retry_after = int(resp.headers.get('Retry-After', 2**attempt)) + logger.warning('Rate limited (429), retrying in %ds (attempt %d/%d)', retry_after, attempt + 1, max_retries) + time.sleep(retry_after) + return resp # unreachable, but keeps type checkers happy + + def _request_raw(self, method: str, url: str, **kwargs) -> httpx.Response: + """Like _request but without raise_for_status — caller handles status codes.""" + max_retries = 3 + for attempt in range(max_retries + 1): + resp = self.client.request(method, url, **kwargs) + if resp.status_code != 429 or attempt == max_retries: + return resp + retry_after = int(resp.headers.get('Retry-After', 2**attempt)) + logger.warning('Rate limited (429), retrying in %ds (attempt %d/%d)', retry_after, attempt + 1, max_retries) + time.sleep(retry_after) + return resp # unreachable + @abstractmethod def list_open_prs(self, repo_slug: str) -> list[PRInfo]: ... diff --git a/src/reviewd/providers/bitbucket.py b/src/reviewd/providers/bitbucket.py index b337623..fe7f872 100644 --- a/src/reviewd/providers/bitbucket.py +++ b/src/reviewd/providers/bitbucket.py @@ -2,7 +2,6 @@ import logging import re -import time import httpx @@ -38,30 +37,6 @@ def __init__(self, workspace: str, auth_token: str): timeout=30, ) - def _request(self, method: str, url: str, **kwargs) -> httpx.Response: - max_retries = 3 - for attempt in range(max_retries + 1): - resp = self.client.request(method, url, **kwargs) - if resp.status_code != 429 or attempt == max_retries: - resp.raise_for_status() - return resp - retry_after = int(resp.headers.get('Retry-After', 2**attempt)) - logger.warning('Rate limited (429), retrying in %ds (attempt %d/%d)', retry_after, attempt + 1, max_retries) - time.sleep(retry_after) - return resp # unreachable, but keeps type checkers happy - - def _request_raw(self, method: str, url: str, **kwargs) -> httpx.Response: - """Like _request but without raise_for_status — caller handles status codes.""" - max_retries = 3 - for attempt in range(max_retries + 1): - resp = self.client.request(method, url, **kwargs) - if resp.status_code != 429 or attempt == max_retries: - return resp - retry_after = int(resp.headers.get('Retry-After', 2**attempt)) - logger.warning('Rate limited (429), retrying in %ds (attempt %d/%d)', retry_after, attempt + 1, max_retries) - time.sleep(retry_after) - return resp # unreachable - def _paginate(self, url: str, params: dict | None = None) -> list[dict]: results = [] seen_ids: set[int] = set() diff --git a/src/reviewd/providers/github.py b/src/reviewd/providers/github.py index cfd8fac..8223b20 100644 --- a/src/reviewd/providers/github.py +++ b/src/reviewd/providers/github.py @@ -1,12 +1,11 @@ from __future__ import annotations import logging -import time import httpx from reviewd.models import GithubConfig, PRInfo -from reviewd.providers.base import GitProvider +from reviewd.providers.base import GitProvider, parse_next_link logger = logging.getLogger(__name__) @@ -26,29 +25,6 @@ def __init__(self, config: GithubConfig): timeout=30, ) - def _request(self, method: str, url: str, **kwargs) -> httpx.Response: - max_retries = 3 - for attempt in range(max_retries + 1): - resp = self.client.request(method, url, **kwargs) - if resp.status_code != 429 or attempt == max_retries: - resp.raise_for_status() - return resp - retry_after = int(resp.headers.get('Retry-After', 2**attempt)) - logger.warning('Rate limited (429), retrying in %ds (attempt %d/%d)', retry_after, attempt + 1, max_retries) - time.sleep(retry_after) - return resp # unreachable - - def _request_raw(self, method: str, url: str, **kwargs) -> httpx.Response: - max_retries = 3 - for attempt in range(max_retries + 1): - resp = self.client.request(method, url, **kwargs) - if resp.status_code != 429 or attempt == max_retries: - return resp - retry_after = int(resp.headers.get('Retry-After', 2**attempt)) - logger.warning('Rate limited (429), retrying in %ds (attempt %d/%d)', retry_after, attempt + 1, max_retries) - time.sleep(retry_after) - return resp # unreachable - def _paginate(self, url: str, params: dict | None = None) -> list[dict]: results = [] params = params or {} @@ -56,7 +32,7 @@ def _paginate(self, url: str, params: dict | None = None) -> list[dict]: resp = self._request('GET', url, params=params) results.extend(resp.json()) link = resp.headers.get('link', '') - next_url = _parse_next_link(link) + next_url = parse_next_link(link) if not next_url: break url = next_url @@ -149,11 +125,3 @@ def approve_pr(self, repo_slug: str, pr_id: int) -> bool: resp.raise_for_status() logger.info('Approved PR #%d', pr_id) return True - - -def _parse_next_link(link_header: str) -> str | None: - for part in link_header.split(','): - if 'rel="next"' in part: - url = part.split(';')[0].strip().strip('<>') - return url - return None diff --git a/src/reviewd/providers/gitlab.py b/src/reviewd/providers/gitlab.py new file mode 100644 index 0000000..5e230b2 --- /dev/null +++ b/src/reviewd/providers/gitlab.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import logging +import re +from dataclasses import dataclass, field +from urllib.parse import quote + +import httpx + +from reviewd.models import GitlabConfig, PRInfo +from reviewd.providers.base import GitProvider, parse_next_link + +logger = logging.getLogger(__name__) + +BOT_MARKER = '[](reviewd)' + +HUNK_HEADER = re.compile(r'^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@') + + +SUGGESTION_BLOCK = re.compile(r'\n*```suggestion\n.*?\n```', re.S) + + +@dataclass +class _FileDiff: + old_path: str + # new line -> old line for every line shown in the diff; None means the line was added + lines: dict[int, int | None] = field(default_factory=dict) + + +def _parse_diff(old_path: str, diff: str) -> _FileDiff: + parsed = _FileDiff(old_path=old_path) + old = new = 0 + for text in diff.splitlines(): + header = HUNK_HEADER.match(text) + if header: + old, new = int(header.group(1)), int(header.group(3)) + elif text.startswith('+'): + parsed.lines[new] = None + new += 1 + elif text.startswith('-'): + old += 1 + elif text.startswith(' ') or text == '': + parsed.lines[new] = old + old += 1 + new += 1 + return parsed + + +def _line_label(line: int | None, end_line: int | None) -> str: + if line is not None and end_line is not None and end_line != line: + return f'Lines {line}-{end_line}' + return f'Line {end_line if end_line is not None else line}' + + +class GitlabProvider(GitProvider): + def __init__(self, config: GitlabConfig): + self.client = httpx.Client( + base_url=f'{config.url.rstrip("/")}/api/v4', + headers={'Authorization': f'Bearer {config.token}'}, + timeout=30, + ) + self._diff_refs: dict[tuple[str, int], dict] = {} + self._file_diffs: dict[tuple[str, int, str], dict[str, _FileDiff]] = {} + + def _paginate(self, url: str, params: dict | None = None) -> list[dict]: + results = [] + while True: + resp = self._request('GET', url, params=params) + results.extend(resp.json()) + next_url = parse_next_link(resp.headers.get('link', '')) + if not next_url: + break + # The next link carries the full query; params={} would make httpx strip it + url = next_url + params = None + return results + + @staticmethod + def _mr_url(repo_slug: str, pr_id: int | None = None) -> str: + url = f'/projects/{quote(repo_slug, safe="")}/merge_requests' + return url if pr_id is None else f'{url}/{pr_id}' + + def _pr_from_data(self, repo_slug: str, data: dict) -> PRInfo: + if data.get('diff_refs'): + self._diff_refs[(repo_slug, data['iid'])] = data['diff_refs'] + return PRInfo( + repo_slug=repo_slug, + pr_id=data['iid'], + title=data['title'], + author=data['author']['username'], + source_branch=data['source_branch'], + destination_branch=data['target_branch'], + source_commit=data['sha'] or '', + url=data['web_url'], + draft=data.get('draft', data.get('work_in_progress', False)), + ) + + def _get_diff_refs(self, repo_slug: str, pr_id: int, source_commit: str | None) -> dict: + refs = self._diff_refs.get((repo_slug, pr_id)) + if refs is None or (source_commit and refs['head_sha'] != source_commit): + self.get_pr(repo_slug, pr_id) + refs = self._diff_refs.get((repo_slug, pr_id)) + if refs is None: + raise RuntimeError(f'MR !{pr_id} has no diff_refs yet, cannot position inline comment') + return refs + + def _get_file_diffs(self, repo_slug: str, pr_id: int, head_sha: str) -> dict[str, _FileDiff]: + key = (repo_slug, pr_id, head_sha) + if key not in self._file_diffs: + files = self._paginate(f'{self._mr_url(repo_slug, pr_id)}/diffs', {'per_page': '100'}) + # Collapsed or too-large files come back with an empty diff; leave them out rather than guess + self._file_diffs[key] = {f['new_path']: _parse_diff(f['old_path'], f['diff']) for f in files if f['diff']} + return self._file_diffs[key] + + @staticmethod + def _line_position(file_diff: _FileDiff | None, file_path: str, line: int) -> dict | None: + if file_diff is None or line not in file_diff.lines: + return None + position = {'position_type': 'text', 'old_path': file_diff.old_path, 'new_path': file_path, 'new_line': line} + old_line = file_diff.lines[line] + if old_line is not None: + position['old_line'] = old_line + return position + + def list_open_prs(self, repo_slug: str) -> list[PRInfo]: + items = self._paginate(self._mr_url(repo_slug), {'state': 'opened', 'per_page': '100'}) + return [self._pr_from_data(repo_slug, item) for item in items] + + def get_pr(self, repo_slug: str, pr_id: int) -> PRInfo: + resp = self._request('GET', self._mr_url(repo_slug, pr_id)) + return self._pr_from_data(repo_slug, resp.json()) + + def post_comment( + self, + repo_slug: str, + pr_id: int, + body: str, + *, + file_path: str | None = None, + line: int | None = None, + end_line: int | None = None, + source_commit: str | None = None, + ) -> int: + marked_body = f'{body}\n\n{BOT_MARKER}' + mr_url = self._mr_url(repo_slug, pr_id) + + if file_path is None: + resp = self._request('POST', f'{mr_url}/notes', json={'body': marked_body}) + comment_id = resp.json()['id'] + else: + refs = self._get_diff_refs(repo_slug, pr_id, source_commit) + position: dict = { + 'base_sha': refs['base_sha'], + 'start_sha': refs['start_sha'], + 'head_sha': refs['head_sha'], + } + file_diff = self._get_file_diffs(repo_slug, pr_id, refs['head_sha']).get(file_path) + target_line = end_line if end_line is not None else line + line_position = None if target_line is None else self._line_position(file_diff, file_path, target_line) + if line_position: + position |= line_position + else: + if target_line is not None: + # A guessed anchor can land on the wrong line; a file-level comment naming the line can't + logger.info('%s:%d is not in the MR diff, posting a file-level comment', file_path, target_line) + label = _line_label(line, end_line) + marked_body = f'{label}: {SUGGESTION_BLOCK.sub("", body)}\n\n{BOT_MARKER}' + old_path = file_diff.old_path if file_diff else file_path + position |= {'position_type': 'file', 'old_path': old_path, 'new_path': file_path} + resp = self._request('POST', f'{mr_url}/discussions', json={'body': marked_body, 'position': position}) + comment_id = resp.json()['notes'][0]['id'] + + logger.info('Posted comment %d on MR !%d', comment_id, pr_id) + return comment_id + + def delete_comment(self, repo_slug: str, pr_id: int, comment_id: int) -> bool: + resp = self._request_raw('DELETE', f'{self._mr_url(repo_slug, pr_id)}/notes/{comment_id}') + if resp.status_code == 204: + logger.info('Deleted comment %d on MR !%d', comment_id, pr_id) + return True + logger.warning('Failed to delete comment %d on MR !%d: %d', comment_id, pr_id, resp.status_code) + return False + + def approve_pr(self, repo_slug: str, pr_id: int) -> bool: + resp = self._request_raw('POST', f'{self._mr_url(repo_slug, pr_id)}/approve') + # GitLab also answers 401 when the user may not approve, so only a token rejected by /user is an auth failure + token_rejected = resp.status_code == 401 and self._request_raw('GET', '/user').status_code == 401 + if token_rejected or (resp.status_code == 403 and 'insufficient_scope' in resp.text): + resp.raise_for_status() + if resp.status_code in (401, 403, 405): + logger.warning('Cannot approve MR !%d (already approved or self-approve): %s', pr_id, resp.text[:200]) + return False + resp.raise_for_status() + logger.info('Approved MR !%d', pr_id) + return True diff --git a/src/reviewd/reviewer.py b/src/reviewd/reviewer.py index c87d7ff..f7d107c 100644 --- a/src/reviewd/reviewer.py +++ b/src/reviewd/reviewer.py @@ -133,8 +133,13 @@ def create_worktree(repo_path: str, pr: PRInfo) -> str: f'{dest_result.stderr.decode().strip()}' ) # Try PR refs (works for forks and deleted branches) - # GitHub: refs/pull//head, BitBucket: refs/pull-requests//from - for pr_ref in [f'pull/{pr.pr_id}/head', f'pull-requests/{pr.pr_id}/from']: + # GitHub: refs/pull//head, BitBucket: refs/pull-requests//from, + # GitLab: refs/merge-requests//head + for pr_ref in [ + f'pull/{pr.pr_id}/head', + f'pull-requests/{pr.pr_id}/from', + f'merge-requests/{pr.pr_id}/head', + ]: ref_result = subprocess.run( ['git', 'fetch', 'origin', pr_ref], cwd=repo_path, diff --git a/src/reviewd/wizard.py b/src/reviewd/wizard.py index b58f2dd..a81e1ab 100644 --- a/src/reviewd/wizard.py +++ b/src/reviewd/wizard.py @@ -13,8 +13,12 @@ REMOTE_PATTERNS = [ (r'github\.com[:/](?P[^/\s]+/[^/\s]+)', 'github'), (r'bitbucket\.org[:/](?P[^/\s]+/[^/\s]+)', 'bitbucket'), + # gitlab.com or a self-hosted instance whose hostname contains "gitlab"; slug may include subgroups + (r'(?:^|@|://)(?P[\w.-]*gitlab[\w.-]*)(?::\d+)?[:/](?P[^\s:]+/[^\s:]+)', 'gitlab'), ] +GITLAB_DEFAULT_URL = 'https://gitlab.com' + STYLE = Style( [ ('qmark', 'fg:cyan bold'), @@ -73,6 +77,9 @@ def _detect_remote(repo_path: str) -> dict | None: elif provider == 'bitbucket': info['workspace'] = parts[0] info['slug'] = parts[-1] + elif provider == 'gitlab': + info['slug'] = slug + info['gitlab_url'] = f'https://{match.group("host")}' return info return None @@ -131,6 +138,20 @@ def _validate_github_token(token: str) -> str | None: return None +def _validate_gitlab_token(url: str, token: str) -> str | None: + try: + resp = httpx.get( + f'{url}/api/v4/user', + headers={'Authorization': f'Bearer {token}'}, + timeout=10, + ) + if resp.status_code == 200: + return resp.json().get('username') + except httpx.HTTPError: + pass + return None + + def _validate_bitbucket_token(token: str, email: str | None = None) -> str | None: try: if email: @@ -183,6 +204,43 @@ def _prompt_github_token(repo_names: list[str]) -> str: _error('Invalid token, try again') +def _prompt_gitlab_tokens(gl_repos: list[dict]) -> dict[str, str]: + """Prompt for a GitLab token per instance. Returns {instance_url: token}.""" + tokens: dict[str, str] = {} + for url in sorted({r['gitlab_url'] for r in gl_repos}): + repos_str = ', '.join(click.style(r['name'], bold=True) for r in gl_repos if r['gitlab_url'] == url) + click.echo(f' GitLab token needed for {url}: {repos_str}') + click.echo() + tokens_url = f'{url}/-/user_settings/personal_access_tokens' + click.echo(' Create a Personal Access Token (or a project/group access token):') + click.echo() + click.echo(f' 1. Go to {click.style(tokens_url, fg="cyan", underline=True)}') + click.echo(' 2. Set a token name (e.g. "reviewd") and expiration') + click.echo(' 3. Scopes → api') + click.echo(' 4. Click "Create token" and paste below') + click.echo() + + while True: + token = questionary.password('GitLab token:', style=STYLE).unsafe_ask() + if not token: + continue + click.echo(' Validating...') + username = _validate_gitlab_token(url, token) + if username: + _success(f'Authenticated as {username}') + tokens[url] = token + break + _error('Invalid token, try again') + return tokens + + +def _gitlab_yaml(token: str, url: str, indent: str) -> list[str]: + lines = [f'{indent}gitlab:', f'{indent} token: "{token}"'] + if url != GITLAB_DEFAULT_URL: + lines.append(f'{indent} url: {url}') + return lines + + def _prompt_bitbucket_tokens(bb_repos: list[dict]) -> dict[str, str]: """Prompt for BitBucket credentials. Returns {workspace: 'token' or 'email:token'}.""" workspaces = list({r['workspace'] for r in bb_repos if r.get('workspace')}) @@ -266,10 +324,18 @@ def _build_global_config_yaml( repos: list[dict], github_token: str | None, bitbucket_creds: dict[str, str], + gitlab_tokens: dict[str, str], cli: str, ) -> str: lines = [] + # One GitLab instance goes in the global section (gitlab.com preferred); others are set per repo + global_gitlab_url = None + if gitlab_tokens: + global_gitlab_url = GITLAB_DEFAULT_URL if GITLAB_DEFAULT_URL in gitlab_tokens else min(gitlab_tokens) + lines.extend(_gitlab_yaml(gitlab_tokens[global_gitlab_url], global_gitlab_url, '')) + lines.append('') + if github_token: lines.append('github:') lines.append(f' token: "{github_token}"') @@ -319,6 +385,10 @@ def _build_global_config_yaml( lines.append(f' workspace: {repo["workspace"]}') if repo.get('slug'): lines.append(f' repo_slug: {repo["slug"]}') + elif repo['provider'] == 'gitlab': + lines.append(f' repo_slug: {repo["slug"]}') + if repo['gitlab_url'] != global_gitlab_url: + lines.extend(_gitlab_yaml(gitlab_tokens[repo['gitlab_url']], repo['gitlab_url'], ' ')) lines.append('') return '\n'.join(lines) @@ -382,6 +452,18 @@ def _build_global_config_yaml( # my-workspace: ATCTT3x... # workspace token # # or: my-workspace: me@example.com:ATATT3x... # user token +# ─── GitLab ─────────────────────────────────────────────────────────── +# Create a Personal Access Token (or a project/group access token): +# 1. Go to https://gitlab.com/-/user_settings/personal_access_tokens +# 2. Set a token name (e.g. "reviewd") and expiration +# 3. Scopes → api +# 4. Create token +# For self-hosted GitLab, set url. A repo can override this with its own gitlab: block. +# +# gitlab: +# token: glpat-YOUR_TOKEN_HERE +# # url: https://gitlab.example.com + # ─── AI CLI ─────────────────────────────────────────────────────────── cli: claude # claude, gemini, or codex # model: claude-sonnet-4-5-20250514 @@ -424,6 +506,12 @@ def _build_global_config_yaml( # provider: bitbucket # workspace: my-workspace # workspace from BitBucket URL # repo_slug: repo-name # repo slug from BitBucket URL + + # GitLab example: + # - name: my-gl-project + # path: /path/to/my-gl-project + # provider: gitlab + # repo_slug: group/subgroup/repo # full project path from GitLab URL """ @@ -459,7 +547,7 @@ def _run_wizard_inner(): click.echo(' Edit the config file to add your tokens and repos:') click.echo(f' {click.style(str(config_path), fg="cyan")}') click.echo() - click.echo(' The file includes instructions for creating GitHub and BitBucket tokens.') + click.echo(' The file includes instructions for creating GitHub, BitBucket and GitLab tokens.') click.echo(' Uncomment and fill in the sections you need.') click.echo() return @@ -510,7 +598,7 @@ def _run_wizard_inner(): available = [r for r in found if r['path'] not in already_paths] if not available: - _info('No repos with recognized remotes (GitHub/BitBucket) found.') + _info('No repos with recognized remotes (GitHub/BitBucket/GitLab) found.') else: # Build choices for checkbox choices = [] @@ -559,6 +647,7 @@ def _run_wizard_inner(): providers = {r['provider'] for r in selected_repos} github_token = None bitbucket_creds: dict[str, str] = {} + gitlab_tokens: dict[str, str] = {} if 'github' in providers: _section('GitHub Credentials') @@ -570,6 +659,11 @@ def _run_wizard_inner(): bb_repos = [r for r in selected_repos if r['provider'] == 'bitbucket'] bitbucket_creds = _prompt_bitbucket_tokens(bb_repos) + if 'gitlab' in providers: + _section('GitLab Credentials') + gl_repos = [r for r in selected_repos if r['provider'] == 'gitlab'] + gitlab_tokens = _prompt_gitlab_tokens(gl_repos) + # 4. AI CLI choice _section('AI CLI') cli = questionary.select( @@ -583,7 +677,7 @@ def _run_wizard_inner(): # 5. Write configs _section('Writing Configuration') - config_yaml = _build_global_config_yaml(selected_repos, github_token, bitbucket_creds, cli) + config_yaml = _build_global_config_yaml(selected_repos, github_token, bitbucket_creds, gitlab_tokens, cli) config_dir.mkdir(parents=True, exist_ok=True) config_path.write_text(config_yaml) _success(f'Created {config_path}') diff --git a/tests/test_config_env.py b/tests/test_config_env.py index 3f9be10..5869de2 100644 --- a/tests/test_config_env.py +++ b/tests/test_config_env.py @@ -1,11 +1,14 @@ -"""Config: env var substitution, max_concurrent_reviews, GIT_TERMINAL_PROMPT.""" +"""Config: env var substitution, max_concurrent_reviews, GIT_TERMINAL_PROMPT, provider resolution.""" from __future__ import annotations import pytest import yaml -from reviewd.config import load_global_config +from reviewd.config import get_provider, load_global_config +from reviewd.providers.bitbucket import BitbucketProvider +from reviewd.providers.github import GithubProvider +from reviewd.providers.gitlab import GitlabProvider def _write_config(tmp_path, data: dict) -> str: @@ -71,3 +74,85 @@ def test_git_env_has_terminal_prompt_disabled(): from reviewd.config import _GIT_ENV as _CONFIG_GIT_ENV assert _CONFIG_GIT_ENV['GIT_TERMINAL_PROMPT'] == '0' + + +def test_gitlab_config_env_vars_and_default_url(tmp_path, monkeypatch): + monkeypatch.setenv('TEST_GL_TOKEN', 'glpat-secret') + path = _write_config( + tmp_path, + { + 'gitlab': {'token': '${TEST_GL_TOKEN}'}, + 'repos': [{'name': 'r', 'path': '/tmp/r', 'provider': 'gitlab', 'repo_slug': 'grp/r'}], + }, + ) + config = load_global_config(path) + assert config.gitlab.token == 'glpat-secret' + assert config.gitlab.url == 'https://gitlab.com' + + +def test_gitlab_url_env_var(tmp_path, monkeypatch): + monkeypatch.setenv('TEST_GL_URL', 'https://gitlab.example.com') + path = _write_config( + tmp_path, + { + 'gitlab': {'token': 't', 'url': '${TEST_GL_URL}'}, + 'repos': [{'name': 'r', 'path': '/tmp/r', 'provider': 'gitlab'}], + }, + ) + assert load_global_config(path).gitlab.url == 'https://gitlab.example.com' + + +def test_gitlab_per_repo_override(tmp_path): + path = _write_config( + tmp_path, + { + 'gitlab': {'token': 'global-token'}, + 'repos': [ + {'name': 'a', 'path': '/tmp/a', 'provider': 'gitlab', 'repo_slug': 'grp/a'}, + { + 'name': 'b', + 'path': '/tmp/b', + 'provider': 'gitlab', + 'repo_slug': 'team/b', + 'gitlab': {'token': 'corp-token', 'url': 'https://gitlab.corp.io'}, + }, + ], + }, + ) + config = load_global_config(path) + provider_a, provider_b = (get_provider(config, repo) for repo in config.repos) + + assert isinstance(provider_a, GitlabProvider) + assert str(provider_a.client.base_url) == 'https://gitlab.com/api/v4/' + assert provider_a.client.headers['Authorization'] == 'Bearer global-token' + assert str(provider_b.client.base_url) == 'https://gitlab.corp.io/api/v4/' + assert provider_b.client.headers['Authorization'] == 'Bearer corp-token' + + +def test_gitlab_missing_config_raises(tmp_path): + path = _write_config( + tmp_path, + {'repos': [{'name': 'lonely', 'path': '/tmp/r', 'provider': 'gitlab'}]}, + ) + config = load_global_config(path) + with pytest.raises(ValueError, match='No gitlab config found for repo "lonely"'): + get_provider(config, config.repos[0]) + + +def test_mixed_providers_resolve_correctly(tmp_path): + path = _write_config( + tmp_path, + { + 'github': {'token': 'gh'}, + 'gitlab': {'token': 'gl'}, + 'bitbucket': {'team': 'bb'}, + 'repos': [ + {'name': 'gh', 'path': '/tmp/gh', 'provider': 'github', 'repo_slug': 'o/gh'}, + {'name': 'gl', 'path': '/tmp/gl', 'provider': 'gitlab', 'repo_slug': 'g/gl'}, + {'name': 'bb', 'path': '/tmp/bb', 'provider': 'bitbucket', 'workspace': 'team'}, + ], + }, + ) + config = load_global_config(path) + providers = [type(get_provider(config, repo)) for repo in config.repos] + assert providers == [GithubProvider, GitlabProvider, BitbucketProvider] diff --git a/tests/test_providers.py b/tests/test_providers.py index 0378b1a..1fccafa 100644 --- a/tests/test_providers.py +++ b/tests/test_providers.py @@ -5,11 +5,13 @@ import json import httpx +import pytest import respx -from reviewd.models import GithubConfig +from reviewd.models import GithubConfig, GitlabConfig from reviewd.providers.bitbucket import BitbucketProvider from reviewd.providers.github import GithubProvider +from reviewd.providers.gitlab import GitlabProvider # --------------------------------------------------------------------------- # GitHub @@ -172,3 +174,383 @@ def test_bitbucket_post_inline_comment(): req = respx.calls.last.request body = req.content.decode() assert 'app.py' in body + + +# --------------------------------------------------------------------------- +# GitLab +# --------------------------------------------------------------------------- + +GL_MRS = 'https://gitlab.com/api/v4/projects/grp%2Fsub%2Frepo/merge_requests' + + +def _gl_mr(iid=7, head_sha='head1', **overrides): + return { + 'iid': iid, + 'title': 'Add feature', + 'author': {'username': 'alice'}, + 'source_branch': 'feat', + 'target_branch': 'main', + 'sha': head_sha, + 'web_url': f'https://gitlab.com/grp/sub/repo/-/merge_requests/{iid}', + 'draft': False, + 'diff_refs': {'base_sha': 'base1', 'start_sha': 'start1', 'head_sha': head_sha}, + **overrides, + } + + +def _gl_provider(**kwargs): + return GitlabProvider(GitlabConfig(token='fake', **kwargs)) + + +GL_DIFF = """@@ -10,4 +10,5 @@ def handler(): + a = 1 +-b = 2 ++c = 3 ++d = 4 + e = 5 + f = 6 +@@ -30,2 +31,3 @@ def other(): + g = 7 ++h = 8 + i = 9 +""" + + +def _gl_diffs(files=None): + if files is None: + files = [{'old_path': 'app.py', 'new_path': 'app.py', 'diff': GL_DIFF}] + return respx.get(f'{GL_MRS}/7/diffs').mock(return_value=httpx.Response(200, json=files)) + + +@respx.mock +def test_gitlab_list_open_prs(): + route = respx.get(GL_MRS).mock(return_value=httpx.Response(200, json=[_gl_mr()])) + prs = _gl_provider().list_open_prs('grp/sub/repo') + assert len(prs) == 1 + pr = prs[0] + assert pr.pr_id == 7 + assert pr.title == 'Add feature' + assert pr.author == 'alice' + assert pr.source_branch == 'feat' + assert pr.destination_branch == 'main' + assert pr.source_commit == 'head1' + assert pr.url == 'https://gitlab.com/grp/sub/repo/-/merge_requests/7' + assert pr.repo_slug == 'grp/sub/repo' + req = route.calls.last.request + assert req.url.params['state'] == 'opened' + assert req.headers['Authorization'] == 'Bearer fake' + + +@respx.mock +def test_gitlab_list_open_prs_follows_pagination_with_query(): + next_url = f'{GL_MRS}?state=opened&per_page=100&page=2' + route = respx.get(GL_MRS).mock( + side_effect=[ + httpx.Response(200, json=[_gl_mr(iid=1)], headers={'link': f'<{next_url}>; rel="next"'}), + httpx.Response(200, json=[_gl_mr(iid=2)]), + ], + ) + prs = _gl_provider().list_open_prs('grp/sub/repo') + assert [p.pr_id for p in prs] == [1, 2] + assert route.call_count == 2 + assert str(route.calls[1].request.url) == next_url + + +@respx.mock +def test_gitlab_encodes_project_path(): + route = respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr())) + _gl_provider().get_pr('grp/sub/repo', 7) + assert route.calls.last.request.url.raw_path.startswith(b'/api/v4/projects/grp%2Fsub%2Frepo/') + + +@pytest.mark.parametrize( + ('fields', 'expected'), + [ + ({'draft': True}, True), + ({'draft': False}, False), + ({'work_in_progress': True}, True), + ({}, False), + ], +) +@respx.mock +def test_gitlab_draft_detection(fields, expected): + mr = _gl_mr() + del mr['draft'] + mr.update(fields) + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=mr)) + assert _gl_provider().get_pr('grp/sub/repo', 7).draft is expected + + +@respx.mock +def test_gitlab_null_sha(): + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr(sha=None, diff_refs=None))) + assert _gl_provider().get_pr('grp/sub/repo', 7).source_commit == '' + + +@respx.mock +def test_gitlab_post_summary_comment(): + route = respx.post(f'{GL_MRS}/7/notes').mock(return_value=httpx.Response(201, json={'id': 555})) + cid = _gl_provider().post_comment('grp/sub/repo', 7, 'Summary') + assert cid == 555 + body = json.loads(route.calls.last.request.content)['body'] + assert body.startswith('Summary') + assert body.endswith('[](reviewd)') + + +@respx.mock +def test_gitlab_post_inline_comment_uses_cached_diff_refs(): + respx.get(GL_MRS).mock(return_value=httpx.Response(200, json=[_gl_mr()])) + get_mr = respx.get(f'{GL_MRS}/7') + route = respx.post(f'{GL_MRS}/7/discussions').mock( + return_value=httpx.Response(201, json={'id': 'disc-1', 'notes': [{'id': 777}]}), + ) + _gl_diffs() + provider = _gl_provider() + provider.list_open_prs('grp/sub/repo') + + cid = provider.post_comment('grp/sub/repo', 7, 'Bug', file_path='app.py', line=12, source_commit='head1') + + assert cid == 777 + assert not get_mr.called + payload = json.loads(route.calls.last.request.content) + assert payload['body'].endswith('[](reviewd)') + assert payload['position'] == { + 'base_sha': 'base1', + 'start_sha': 'start1', + 'head_sha': 'head1', + 'old_path': 'app.py', + 'new_path': 'app.py', + 'position_type': 'text', + 'new_line': 12, + } + + +@respx.mock +def test_gitlab_post_inline_comment_fetches_diff_refs_when_not_cached(): + get_mr = respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr())) + route = respx.post(f'{GL_MRS}/7/discussions').mock( + return_value=httpx.Response(201, json={'notes': [{'id': 1}]}), + ) + _gl_diffs() + _gl_provider().post_comment('grp/sub/repo', 7, 'Bug', file_path='app.py', line=3) + assert get_mr.call_count == 1 + assert json.loads(route.calls.last.request.content)['position']['head_sha'] == 'head1' + + +@respx.mock +def test_gitlab_post_inline_comment_refetches_when_head_moved(): + respx.get(GL_MRS).mock(return_value=httpx.Response(200, json=[_gl_mr(head_sha='old')])) + get_mr = respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr(head_sha='new'))) + route = respx.post(f'{GL_MRS}/7/discussions').mock( + return_value=httpx.Response(201, json={'notes': [{'id': 1}]}), + ) + _gl_diffs() + provider = _gl_provider() + provider.list_open_prs('grp/sub/repo') + + provider.post_comment('grp/sub/repo', 7, 'Bug', file_path='app.py', line=3, source_commit='new') + + assert get_mr.call_count == 1 + assert json.loads(route.calls.last.request.content)['position']['head_sha'] == 'new' + + +@respx.mock +def test_gitlab_post_file_level_comment(): + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr())) + route = respx.post(f'{GL_MRS}/7/discussions').mock( + return_value=httpx.Response(201, json={'notes': [{'id': 1}]}), + ) + _gl_diffs() + _gl_provider().post_comment('grp/sub/repo', 7, 'Whole file', file_path='app.py') + position = json.loads(route.calls.last.request.content)['position'] + assert position['position_type'] == 'file' + assert 'new_line' not in position + + +@respx.mock +def test_gitlab_post_range_comment_anchors_on_end_line(): + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr())) + route = respx.post(f'{GL_MRS}/7/discussions').mock( + return_value=httpx.Response(201, json={'notes': [{'id': 1}]}), + ) + _gl_diffs() + _gl_provider().post_comment('grp/sub/repo', 7, 'Range', file_path='app.py', line=10, end_line=14) + assert json.loads(route.calls.last.request.content)['position']['new_line'] == 14 + + +@pytest.mark.parametrize( + ('line', 'old_line'), + [ + (10, 10), # context line inside a hunk + (11, None), # added line + (13, 12), # context line after a removal and two additions + (32, None), # added line in the second hunk + (33, 31), # context line in the second hunk + ], +) +@respx.mock +def test_gitlab_inline_comment_line_mapping(line, old_line): + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr())) + _gl_diffs() + route = respx.post(f'{GL_MRS}/7/discussions').mock(return_value=httpx.Response(201, json={'notes': [{'id': 1}]})) + + _gl_provider().post_comment('grp/sub/repo', 7, 'Bug', file_path='app.py', line=line, source_commit='head1') + + position = json.loads(route.calls.last.request.content)['position'] + assert position['new_line'] == line + assert position.get('old_line') == old_line + + +@respx.mock +def test_gitlab_inline_comment_on_renamed_file_uses_old_path(): + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr())) + _gl_diffs([{'old_path': 'old/app.py', 'new_path': 'app.py', 'diff': GL_DIFF}]) + route = respx.post(f'{GL_MRS}/7/discussions').mock(return_value=httpx.Response(201, json={'notes': [{'id': 1}]})) + + _gl_provider().post_comment('grp/sub/repo', 7, 'Bug', file_path='app.py', line=13, source_commit='head1') + + position = json.loads(route.calls.last.request.content)['position'] + assert (position['old_path'], position['new_path'], position['old_line']) == ('old/app.py', 'app.py', 12) + + +@pytest.mark.parametrize( + ('files', 'line', 'end_line', 'label', 'old_path'), + [ + ([{'old_path': 'app.py', 'new_path': 'app.py', 'diff': GL_DIFF}], 5, None, 'Line 5', 'app.py'), + ([{'old_path': 'app.py', 'new_path': 'app.py', 'diff': GL_DIFF}], 20, None, 'Line 20', 'app.py'), + ([{'old_path': 'app.py', 'new_path': 'app.py', 'diff': GL_DIFF}], 40, None, 'Line 40', 'app.py'), + ([{'old_path': 'app.py', 'new_path': 'app.py', 'diff': GL_DIFF}], 3, 5, 'Lines 3-5', 'app.py'), + ([{'old_path': 'old/app.py', 'new_path': 'app.py', 'diff': GL_DIFF}], 20, None, 'Line 20', 'old/app.py'), + ([{'old_path': 'app.py', 'new_path': 'app.py', 'diff': ''}], 13, None, 'Line 13', 'app.py'), # collapsed + ([{'old_path': 'other.py', 'new_path': 'other.py', 'diff': GL_DIFF}], 13, None, 'Line 13', 'app.py'), + ], +) +@respx.mock +def test_gitlab_unclassifiable_line_falls_back_to_file_comment(files, line, end_line, label, old_path): + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr())) + _gl_diffs(files) + route = respx.post(f'{GL_MRS}/7/discussions').mock(return_value=httpx.Response(201, json={'notes': [{'id': 1}]})) + body = '🔴 **Bug**\n\nSomething is off.\n\n```suggestion\nfixed = True\n```' + + _gl_provider().post_comment( + 'grp/sub/repo', 7, body, file_path='app.py', line=line, end_line=end_line, source_commit='head1' + ) + + payload = json.loads(route.calls.last.request.content) + assert payload['position']['position_type'] == 'file' + assert (payload['position']['old_path'], payload['position']['new_path']) == (old_path, 'app.py') + assert 'new_line' not in payload['position'] + assert 'old_line' not in payload['position'] + assert payload['body'] == f'{label}: 🔴 **Bug**\n\nSomething is off.\n\n[](reviewd)' + + +@respx.mock +def test_gitlab_diff_fetched_once_per_head_commit(): + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr())) + diffs = _gl_diffs() + respx.post(f'{GL_MRS}/7/discussions').mock(return_value=httpx.Response(201, json={'notes': [{'id': 1}]})) + provider = _gl_provider() + + for line in (10, 13, 20): + provider.post_comment('grp/sub/repo', 7, 'Bug', file_path='app.py', line=line, source_commit='head1') + + assert diffs.call_count == 1 + + +@pytest.mark.parametrize(('status', 'expected'), [(204, True), (404, False)]) +@respx.mock +def test_gitlab_delete_comment(status, expected): + route = respx.delete(f'{GL_MRS}/7/notes/777').mock(return_value=httpx.Response(status)) + assert _gl_provider().delete_comment('grp/sub/repo', 7, 777) is expected + assert route.called + + +@respx.mock +def test_gitlab_approve_success(): + respx.post(f'{GL_MRS}/7/approve').mock(return_value=httpx.Response(201, json={})) + assert _gl_provider().approve_pr('grp/sub/repo', 7) is True + + +@pytest.mark.parametrize('status', [403, 405]) +@respx.mock +def test_gitlab_approve_refused_returns_gracefully(status): + respx.post(f'{GL_MRS}/7/approve').mock(return_value=httpx.Response(status, json={'message': 'nope'})) + assert _gl_provider().approve_pr('grp/sub/repo', 7) is False + + +@respx.mock +def test_gitlab_approve_401_with_valid_token_returns_gracefully(): + respx.post(f'{GL_MRS}/7/approve').mock(return_value=httpx.Response(401, json={'message': '401 Unauthorized'})) + user = respx.get('https://gitlab.com/api/v4/user').mock(return_value=httpx.Response(200, json={'username': 'bot'})) + assert _gl_provider().approve_pr('grp/sub/repo', 7) is False + assert user.called + + +@respx.mock +def test_gitlab_approve_401_with_rejected_token_raises(): + respx.post(f'{GL_MRS}/7/approve').mock(return_value=httpx.Response(401, json={'message': '401 Unauthorized'})) + respx.get('https://gitlab.com/api/v4/user').mock(return_value=httpx.Response(401)) + with pytest.raises(httpx.HTTPStatusError) as exc: + _gl_provider().approve_pr('grp/sub/repo', 7) + assert exc.value.request.url.path.endswith('/approve') + + +@respx.mock +def test_gitlab_approve_insufficient_scope_raises(): + respx.post(f'{GL_MRS}/7/approve').mock( + return_value=httpx.Response(403, json={'error': 'insufficient_scope', 'scope': 'api'}), + ) + with pytest.raises(httpx.HTTPStatusError): + _gl_provider().approve_pr('grp/sub/repo', 7) + + +@respx.mock +def test_gitlab_approve_server_error_raises(): + respx.post(f'{GL_MRS}/7/approve').mock(return_value=httpx.Response(500)) + with pytest.raises(httpx.HTTPStatusError): + _gl_provider().approve_pr('grp/sub/repo', 7) + + +@respx.mock +def test_gitlab_retries_on_rate_limit(monkeypatch): + sleeps = [] + monkeypatch.setattr('reviewd.providers.base.time.sleep', sleeps.append) + route = respx.get(f'{GL_MRS}/7').mock( + side_effect=[ + httpx.Response(429, headers={'Retry-After': '3'}), + httpx.Response(200, json=_gl_mr()), + ], + ) + assert _gl_provider().get_pr('grp/sub/repo', 7).pr_id == 7 + assert route.call_count == 2 + assert sleeps == [3] + + +@respx.mock +def test_gitlab_inline_comment_without_diff_refs_raises_clear_error(): + respx.get(f'{GL_MRS}/7').mock(return_value=httpx.Response(200, json=_gl_mr(diff_refs=None))) + discussions = respx.post(f'{GL_MRS}/7/discussions') + with pytest.raises(RuntimeError, match='MR !7 has no diff_refs yet'): + _gl_provider().post_comment('grp/sub/repo', 7, 'body', file_path='a.py', line=3, source_commit='head1') + assert not discussions.called + + +@pytest.mark.parametrize( + ('url', 'expected'), + [ + ('https://gitlab.example.com', 'https://gitlab.example.com/api/v4/'), + ('https://gitlab.example.com/', 'https://gitlab.example.com/api/v4/'), + ('https://example.com/gitlab/', 'https://example.com/gitlab/api/v4/'), + ], +) +def test_gitlab_base_url(url, expected): + assert str(_gl_provider(url=url).client.base_url) == expected + + +@respx.mock +def test_gitlab_self_hosted_with_subpath_requests(): + route = respx.get('https://example.com/gitlab/api/v4/projects/grp%2Frepo/merge_requests/3').mock( + return_value=httpx.Response(200, json=_gl_mr(iid=3)), + ) + _gl_provider(url='https://example.com/gitlab').get_pr('grp/repo', 3) + assert route.called diff --git a/tests/test_review_cycle.py b/tests/test_review_cycle.py index 1a9efb9..a456670 100644 --- a/tests/test_review_cycle.py +++ b/tests/test_review_cycle.py @@ -2,10 +2,13 @@ from __future__ import annotations +import httpx +import respx from helpers import AI_JSON_OUTPUT, make_finding, make_result from reviewd.commenter import post_review -from reviewd.models import ProjectConfig, Severity +from reviewd.models import GitlabConfig, ProjectConfig, Severity +from reviewd.providers.gitlab import GitlabProvider from reviewd.reviewer import extract_json, parse_review_result @@ -97,3 +100,88 @@ def test_dry_run_posts_nothing(provider, state_db, pr, global_config, project_co out = capsys.readouterr().out assert 'DRY RUN' in out assert 'Test finding' in out + + +GL_MR = 'https://gitlab.com/api/v4/projects/team%2Fmy-repo/merge_requests/42' + + +def _mock_gitlab_mr(): + respx.get(GL_MR).mock( + return_value=httpx.Response( + 200, + json={ + 'iid': 42, + 'title': 'Fix bug in parser', + 'author': {'username': 'alice'}, + 'source_branch': 'fix/parser', + 'target_branch': 'main', + 'sha': 'abc1234567890', # pragma: allowlist secret + 'web_url': 'https://gitlab.com/team/my-repo/-/merge_requests/42', + 'diff_refs': {'base_sha': 'b', 'start_sha': 's', 'head_sha': 'abc1234567890'}, + }, + ), + ) + respx.get(f'{GL_MR}/diffs').mock(return_value=httpx.Response(200, json=[])) + + +@respx.mock +def test_gitlab_inline_rejected_still_posts_rest(state_db, pr, global_config): + """GitLab rejects an inline comment on a line outside the diff → skipped, others + summary posted.""" + _mock_gitlab_mr() + discussions = respx.post(f'{GL_MR}/discussions').mock( + side_effect=[ + httpx.Response(400, json={'message': {'line_code': ["can't be blank"]}}), + httpx.Response(201, json={'notes': [{'id': 2}]}), + ], + ) + notes = respx.post(f'{GL_MR}/notes').mock(return_value=httpx.Response(201, json={'id': 3})) + result = make_result( + [ + make_finding(severity='critical', title='Outside diff', line=999), + make_finding(severity='critical', title='Inside diff', line=10), + ] + ) + provider = GitlabProvider(GitlabConfig(token='fake')) + + post_review(provider, state_db, pr, result, ProjectConfig(inline_comments_for=['critical']), global_config) + + assert discussions.call_count == 2 + assert notes.call_count == 1 + assert sorted(state_db.get_comment_ids(pr.repo_slug, pr.pr_id)) == [2, 3] + + +@respx.mock +def test_gitlab_re_review_deletes_old_notes(state_db, pr, global_config): + _mock_gitlab_mr() + respx.post(f'{GL_MR}/discussions').mock( + side_effect=[ + httpx.Response(201, json={'notes': [{'id': 10}]}), + httpx.Response(201, json={'notes': [{'id': 20}]}), + ], + ) + respx.post(f'{GL_MR}/notes').mock( + side_effect=[httpx.Response(201, json={'id': 11}), httpx.Response(201, json={'id': 21})], + ) + deletes = respx.delete(url__regex=rf'{GL_MR}/notes/\d+').mock(return_value=httpx.Response(204)) + result = make_result([make_finding(severity='critical')]) + project_config = ProjectConfig(inline_comments_for=['critical']) + + post_review(GitlabProvider(GitlabConfig(token='fake')), state_db, pr, result, project_config, global_config) + post_review(GitlabProvider(GitlabConfig(token='fake')), state_db, pr, result, project_config, global_config) + + deleted = sorted(int(str(call.request.url).rsplit('/', 1)[1]) for call in deletes.calls) + assert deleted == [10, 11] + assert sorted(state_db.get_comment_ids(pr.repo_slug, pr.pr_id)) == [20, 21] + + +@respx.mock +def test_gitlab_critical_task_is_skipped(state_db, pr, global_config): + """critical_task is BitBucket-only; on GitLab no task endpoints are touched.""" + respx.post(f'{GL_MR}/notes').mock(return_value=httpx.Response(201, json={'id': 1})) + unexpected = respx.route().mock(return_value=httpx.Response(404)) + result = make_result([make_finding(severity='critical')]) + project_config = ProjectConfig(inline_comments_for=[], critical_task=True) + + post_review(GitlabProvider(GitlabConfig(token='fake')), state_db, pr, result, project_config, global_config) + + assert not unexpected.called diff --git a/tests/test_wizard.py b/tests/test_wizard.py new file mode 100644 index 0000000..b3a80f3 --- /dev/null +++ b/tests/test_wizard.py @@ -0,0 +1,138 @@ +"""Wizard: remote detection, token validation, generated config round trip.""" + +from __future__ import annotations + +import subprocess + +import httpx +import pytest +import respx + +from reviewd.config import get_provider, load_global_config +from reviewd.wizard import _build_global_config_yaml, _detect_remote, _validate_gitlab_token + + +def _repo_with_remote(tmp_path, url: str) -> str: + repo = tmp_path / 'myrepo' + repo.mkdir() + subprocess.run(['git', 'init', '-q'], cwd=repo, check=True) + subprocess.run(['git', 'remote', 'add', 'origin', url], cwd=repo, check=True) + return str(repo) + + +@pytest.mark.parametrize( + ('url', 'slug', 'gitlab_url'), + [ + ('git@gitlab.com:grp/sub/repo.git', 'grp/sub/repo', 'https://gitlab.com'), + ('https://gitlab.com/grp/repo.git', 'grp/repo', 'https://gitlab.com'), + ('https://gitlab.com/grp/repo', 'grp/repo', 'https://gitlab.com'), + ('ssh://git@gitlab.corp.io:2222/team/svc.git', 'team/svc', 'https://gitlab.corp.io'), + ('https://oauth2:tok@gitlab.corp.io/team/a/b.git', 'team/a/b', 'https://gitlab.corp.io'), + ], +) +def test_detect_gitlab_remote(tmp_path, url, slug, gitlab_url): + info = _detect_remote(_repo_with_remote(tmp_path, url)) + assert info['provider'] == 'gitlab' + assert info['slug'] == slug + assert info['gitlab_url'] == gitlab_url + assert info['name'] == 'myrepo' + + +@pytest.mark.parametrize( + ('url', 'provider'), + [ + ('git@github.com:owner/gitlab-mirror.git', 'github'), + ('git@bitbucket.org:ws/gitlab-tools.git', 'bitbucket'), + ], +) +def test_detect_non_gitlab_remote_mentioning_gitlab(tmp_path, url, provider): + assert _detect_remote(_repo_with_remote(tmp_path, url))['provider'] == provider + + +@pytest.mark.parametrize( + 'url', + [ + 'git@git.example.com:team/repo.git', + 'https://example.com/gitlab/grp/repo.git', + 'git@git.example.com:gitlab/sub/repo.git', + ], +) +def test_detect_unknown_remote(tmp_path, url): + assert _detect_remote(_repo_with_remote(tmp_path, url)) is None + + +def _gitlab_repo(name: str, slug: str, gitlab_url: str) -> dict: + return {'name': name, 'path': f'/tmp/{name}', 'provider': 'gitlab', 'slug': slug, 'gitlab_url': gitlab_url} + + +def test_config_yaml_single_gitlab_com_instance(): + text = _build_global_config_yaml( + [_gitlab_repo('a', 'grp/a', 'https://gitlab.com')], + None, + {}, + {'https://gitlab.com': 'tok'}, + 'claude', + ) + assert text.startswith('gitlab:\n token: "tok"\n\n') + assert 'url:' not in text + assert ' repo_slug: grp/a' in text + + +def test_config_yaml_self_hosted_instance_writes_url(): + text = _build_global_config_yaml( + [_gitlab_repo('a', 'grp/a', 'https://gitlab.corp.io')], + None, + {}, + {'https://gitlab.corp.io': 'tok'}, + 'claude', + ) + assert text.startswith('gitlab:\n token: "tok"\n url: https://gitlab.corp.io\n') + + +def test_config_yaml_round_trip_multiple_instances(tmp_path): + text = _build_global_config_yaml( + [ + _gitlab_repo('a', 'grp/a', 'https://gitlab.com'), + _gitlab_repo('b', 'team/sub/b', 'https://gitlab.corp.io'), + ], + None, + {}, + {'https://gitlab.corp.io': 'corp-tok', 'https://gitlab.com': 'com-tok'}, + 'claude', + ) + path = tmp_path / 'config.yaml' + path.write_text(text) + config = load_global_config(str(path)) + + assert config.gitlab.url == 'https://gitlab.com' + assert config.gitlab.token == 'com-tok' + repo_a, repo_b = config.repos + assert repo_a.gitlab is None + assert repo_b.slug == 'team/sub/b' + + provider_a, provider_b = get_provider(config, repo_a), get_provider(config, repo_b) + assert str(provider_a.client.base_url) == 'https://gitlab.com/api/v4/' + assert provider_a.client.headers['Authorization'] == 'Bearer com-tok' + assert str(provider_b.client.base_url) == 'https://gitlab.corp.io/api/v4/' + assert provider_b.client.headers['Authorization'] == 'Bearer corp-tok' + + +@respx.mock +def test_validate_gitlab_token_success(): + route = respx.get('https://gitlab.corp.io/api/v4/user').mock( + return_value=httpx.Response(200, json={'username': 'alice'}), + ) + assert _validate_gitlab_token('https://gitlab.corp.io', 'tok') == 'alice' + assert route.calls.last.request.headers['Authorization'] == 'Bearer tok' + + +@respx.mock +def test_validate_gitlab_token_rejected(): + respx.get('https://gitlab.com/api/v4/user').mock(return_value=httpx.Response(401)) + assert _validate_gitlab_token('https://gitlab.com', 'bad') is None + + +@respx.mock +def test_validate_gitlab_token_network_error(): + respx.get('https://gitlab.com/api/v4/user').mock(side_effect=httpx.ConnectError('unreachable')) + assert _validate_gitlab_token('https://gitlab.com', 'tok') is None