Bitbucket Pipeline action for AI-powered code review using Google Gemini
npm install bitbucket-gemini-actionAI-powered code review for Bitbucket using Google Gemini. Automatically review pull requests, respond to mentions, and provide intelligent code feedback.
| Variable | Value |
|----------|-------|
| GEMINI_API_KEY | your-gemini-api-key |
| BITBUCKET_ACCESS_TOKEN | your-bitbucket-token |
bitbucket-pipelines.yml 파일 생성/수정:``yaml
image: node:20
pipelines:
pull-requests:
'**':
- step:
name: AI Code Review
script:
- curl -fsSL https://bun.sh/install | bash
- export PATH="$HOME/.bun/bin:$PATH"
# 리뷰 스타일 커스터마이징 (선택)
- export REVIEW_PRESETS="middle,nextjs,typescript,security"
# 자동 리뷰 활성화 (선택)
- export PROMPT="이 PR을 리뷰해주세요"
- npx bitbucket-gemini-action
`
REVIEW_PRESETS 환경변수로 원하는 리뷰 관점을 ,로 구분해서 조합:
`yaml주니어 개발자 대상 + React 프로젝트
- export REVIEW_PRESETS="junior,react,frontend"
프리셋 종류 (src/gemini/presets.ts 참고):
- 경험 레벨:
junior, middle, senior, lead
- 프레임워크: react, nextjs, vue, nestjs, express, django 등
- 관점: security, performance, architecture, testing, accessibility
- AI/ML: chatbot, rag, llmIntegration, aiAgent, langchain, vectorDB
- 언어: typescript, javascript, python, go, java, rust
- 품질: cleanCode, refactoring, documentation, maintainability$3
- PR 생성/업데이트 시: 자동으로 AI 코드 리뷰 실행 (PROMPT 설정한 경우)
- @gemini 멘션 기능 (선택사항): PR 코멘트에 @gemini 이 함수 설명해줘 입력하면 AI가 응답
- 아래 두 가지 추가 설정 필요:#### 5-1. 웹훅 설정 (멘션 기능용)
1. Repository Settings → Webhooks → Add webhook
2. 다음 정보 입력:
- Title:
bitbucket-gemini
- URL: https://bitbucket-gemini-webhook.ainetwork.workers.dev
- Triggers: ✅ Pull request: Comment created & Comment updated
3. Save 클릭#### 5-2. 파이프라인에 멘션 핸들러 추가
bitbucket-pipelines.yml에 다음 추가:`yaml
pipelines:
custom:
gemini-comment:
- step:
name: Gemini Comment Handler
script:
- curl -fsSL https://bun.sh/install | bash
- export PATH="$HOME/.bun/bin:$PATH"
- npx bitbucket-gemini-action
`---
Features
- 🤖 AI Code Review: Automatically analyze PRs for bugs, security issues, and code quality
- 💬 @gemini Mentions: Respond to questions and requests in PR comments
- 🔧 Inline Comments: Post targeted feedback on specific lines of code
- 📊 Progress Tracking: Visual tracking comments show review progress
- 🔄 Two Modes: Tag mode (interactive) and Agent mode (automated)
Quick Start
$3
Go to Repository settings > Repository variables and add:
| Variable | Required | Description |
|----------|----------|-------------|
|
GEMINI_API_KEY | Yes | Your Google Gemini API key |
| BITBUCKET_ACCESS_TOKEN | Yes* | Bitbucket access token with PR permissions |
| BITBUCKET_USERNAME | Yes* | Username for basic auth |
| BITBUCKET_APP_PASSWORD | Yes* | App password for basic auth |*Either
BITBUCKET_ACCESS_TOKEN OR both BITBUCKET_USERNAME and BITBUCKET_APP_PASSWORD are required.$3
Create or update your
bitbucket-pipelines.yml:`yaml
image: node:20pipelines:
pull-requests:
'**':
- step:
name: AI Code Review
script:
- curl -fsSL https://bun.sh/install | bash
- export PATH="$HOME/.bun/bin:$PATH"
- npx bitbucket-gemini-action
`$3
Automatic Review: PRs are automatically reviewed when opened or updated.
Manual Trigger: Comment
@gemini followed by your request:
- @gemini review this PR
- @gemini what does this function do?
- @gemini check for security issues> Note:
@gemini 멘션 기능을 사용하려면 웹훅 설정이 필요합니다.Configuration
$3
| Variable | Default | Description |
|----------|---------|-------------|
|
GEMINI_API_KEY | - | Google Gemini API key |
| GOOGLE_API_KEY | - | Alternative to GEMINI_API_KEY |
| TRIGGER_PHRASE | @gemini | Phrase to trigger bot |
| GEMINI_MODEL | gemini-2.0-flash | Gemini model to use |
| MODE | auto | tag or agent |
| CREATE_TRACKING_COMMENT | true | Show progress comment |
| PROMPT | - | Custom prompt for agent mode |$3
-
gemini-2.0-flash (default) - Fast and efficient
- gemini-2.0-flash-lite - Faster, lower cost
- gemini-1.5-pro - More capable, slower
- gemini-1.5-flash - Balanced optionReview Presets
리뷰 프리셋을 사용하여 리뷰 스타일과 관점을 커스터마이징할 수 있습니다.
$3
| Variable | Description |
|----------|-------------|
|
REVIEW_PRESETS | 쉼표로 구분된 프리셋 키 목록 (예: junior,nextjs,security) |
| CUSTOM_PROMPT | 추가 커스텀 프롬프트 |$3
`yaml
주니어 개발자 + Next.js 프로젝트
- step:
script:
- export REVIEW_PRESETS="junior,nextjs"
- npx bitbucket-gemini-action시니어 + 아키텍처 + 보안 리뷰
- step:
script:
- export REVIEW_PRESETS="senior,architecture,security"
- npx bitbucket-gemini-action챗봇 프로젝트 + RAG 시스템
- step:
script:
- export REVIEW_PRESETS="chatbot,rag,typescript"
- npx bitbucket-gemini-action커스텀 프롬프트 추가
- step:
script:
- export REVIEW_PRESETS="middle,nestjs"
- export CUSTOM_PROMPT="특히 DB 쿼리 최적화에 집중해주세요"
- npx bitbucket-gemini-action
`$3
#### 경험 레벨 (Experience)
| Key | Name | Description |
|-----|------|-------------|
|
junior | 주니어 개발자용 | 친절하고 교육적인 리뷰, 기본 개념 설명 포함 |
| middle | 미들급 개발자용 | 디자인 패턴, 트레이드오프 분석 |
| senior | 시니어 개발자용 | 아키텍처 수준 피드백, 간결한 분석 |
| lead | 테크 리드용 | 팀 관점, 멘토링 기회 식별 |#### 리뷰 관점 (Perspective)
| Key | Name | Description |
|-----|------|-------------|
|
architecture | 아키텍처/설계 | SOLID, 모듈화, 확장성 |
| security | 보안 | 취약점, 인증/인가, 민감 데이터 |
| performance | 성능 | 알고리즘, DB, 메모리, 비동기 |
| testing | 테스트 | 커버리지, 테스트 품질, 모킹 |
| accessibility | 접근성 (a11y) | 시맨틱 HTML, ARIA, 키보드 |
| errorHandling | 에러 핸들링 | 예외 처리, 복구 전략 |
| codeStyle | 코드 스타일 | 네이밍, 가독성, 일관성 |#### 프레임워크 (Framework)
| Key | Name | Description |
|-----|------|-------------|
|
react | React | Hooks, 컴포넌트 설계, 상태 관리 |
| nextjs | Next.js | App Router, Server Components, Data Fetching |
| vue | Vue.js | Composition API, Composables |
| angular | Angular | 모듈, DI, RxJS |
| nestjs | NestJS | 모듈, Guard/Pipe, DTO |
| express | Express.js | 미들웨어, 라우팅, 보안 |
| fastify | Fastify | 플러그인, 스키마, 훅 |
| springboot | Spring Boot | 레이어, JPA, Security |
| django | Django | 모델, ORM, DRF |
| flask | Flask | 블루프린트, SQLAlchemy |#### 도메인 (Domain)
| Key | Name | Description |
|-----|------|-------------|
|
frontend | 프론트엔드 일반 | UI/UX, 상태 관리, 스타일링 |
| backend | 백엔드 일반 | API 설계, DB, 인증 |
| fullstack | 풀스택 | API 계약, 데이터 흐름 |
| mobile | 모바일 | React Native, Flutter |
| devops | DevOps/인프라 | CI/CD, IaC, K8s |
| database | 데이터베이스 | 스키마, 인덱스, 쿼리 |#### 프로그래밍 언어 (Language)
| Key | Name | Description |
|-----|------|-------------|
|
typescript | TypeScript | 타입 시스템, 제네릭, 유틸리티 타입 |
| javascript | JavaScript | ES6+, 비동기, 모듈 |
| python | Python | PEP 8, Pythonic 코드 |
| go | Go | 관용구, 동시성, 에러 처리 |
| java | Java | 모던 Java, OOP, 동시성 |
| rust | Rust | 소유권, 에러 처리, 동시성 |#### AI/ML
| Key | Name | Description |
|-----|------|-------------|
|
chatbot | 챗봇/대화형 AI | 대화 관리, 프롬프트, RAG |
| llmIntegration | LLM API 통합 | API 클라이언트, 에러 처리, 비용 |
| rag | RAG 시스템 | 문서 처리, 임베딩, 검색 |
| aiAgent | AI 에이전트 | 계획-실행, 도구 사용, 안전성 |
| mlOps | MLOps | 모델 관리, 파이프라인, 모니터링 |
| promptEngineering | 프롬프트 엔지니어링 | 프롬프트 설계, 최적화 |
| vectorDB | 벡터 데이터베이스 | 인덱스, 쿼리 최적화 |
| langchain | LangChain | 체인, 에이전트, 메모리 |#### 코드 품질 (Quality)
| Key | Name | Description |
|-----|------|-------------|
|
cleanCode | 클린 코드 | 클린 코드 원칙 |
| refactoring | 리팩토링 기회 | 코드 스멜 식별 |
| documentation | 문서화 | API 문서, 주석 |
| maintainability | 유지보수성 | 가독성, 모듈성, 테스트 가능성 |$3
`yaml
프론트엔드 팀
REVIEW_PRESETS="junior,react,frontend,accessibility"백엔드 팀
REVIEW_PRESETS="middle,nestjs,backend,security,performance"AI/챗봇 팀
REVIEW_PRESETS="senior,chatbot,rag,langchain,typescript"풀스택 코드 리뷰
REVIEW_PRESETS="middle,nextjs,nestjs,fullstack"코드 품질 중심
REVIEW_PRESETS="cleanCode,refactoring,maintainability,testing"
`Modes
$3
Triggered by
@gemini mentions in comments. Responds directly to user requests.`
@gemini Can you explain what this function does?
`$3
Triggered by providing a
PROMPT variable. Executes predefined tasks automatically.`yaml
- step:
script:
- export PROMPT="Review for security vulnerabilities"
- npx bitbucket-gemini-action
`$3
두 기능을 동시에 사용하려면:
1. 자동 리뷰:
PROMPT 환경변수로 PR 생성/업데이트 시 자동 실행
2. @gemini 멘션: 웹훅으로 코멘트 이벤트 수신 시 실행`yaml
image: node:20pipelines:
pull-requests:
'**':
- step:
name: AI Code Review
script:
- export PROMPT="Review this PR"
- export ALLOW_BOTS=true
- export REVIEW_PRESETS="middle,nextjs,typescript"
- npx bitbucket-gemini-action@latest
custom:
gemini-comment:
- step:
name: Gemini Comment Handler
script:
- export ALLOW_BOTS=true
- npx bitbucket-gemini-action@latest
`-
pull-requests 파이프라인: PR 생성/업데이트 시 자동 리뷰
- custom/gemini-comment 파이프라인: 웹훅에서 코멘트 이벤트 수신 시 @gemini 멘션 처리Webhook Setup for @gemini Mentions
@gemini 멘션 기능을 사용하려면 Bitbucket 웹훅과 중간 서버가 필요합니다.$3
Bitbucket Pipelines는 외부 웹훅 URL로 직접 트리거할 수 없습니다. 따라서:
1. 웹훅 → 중간 서버 → Bitbucket API로 파이프라인 트리거
$3
AWS Lambda, Cloudflare Workers, 또는 별도 서버에서 웹훅을 수신하고 Bitbucket API를 호출:
`javascript
// Cloudflare Worker 예시
export default {
async fetch(request, env) {
const payload = await request.json(); // @gemini 멘션 확인
if (!payload.comment?.content?.raw?.includes('@gemini')) {
return new Response('No trigger', { status: 200 });
}
// Bitbucket Pipeline API 호출
const response = await fetch(
https://api.bitbucket.org/2.0/repositories/${payload.repository.full_name}/pipelines/,
{
method: 'POST',
headers: {
'Authorization': Bearer ${env.BITBUCKET_ACCESS_TOKEN},
'Content-Type': 'application/json',
},
body: JSON.stringify({
target: {
ref_type: 'branch',
type: 'pipeline_ref_target',
ref_name: payload.pullrequest.source.branch.name,
selector: {
type: 'custom',
pattern: 'gemini-comment',
},
},
variables: [
{ key: 'WEBHOOK_PAYLOAD', value: JSON.stringify(payload) },
{ key: 'TRIGGER_EVENT', value: 'pullrequest:comment_created' },
],
}),
}
); return new Response('Pipeline triggered', { status: 200 });
},
};
`$3
더 깊은 통합이 필요하면 Bitbucket Connect 앱을 개발하세요.
$3
1. Repository Settings → Webhooks → Add webhook
2. Title:
bitbucket-gemini
3. URL: 중간 서버 URL (예: https://your-worker.workers.dev/webhook)
4. Triggers 선택:
- ✅ Pull request: Comment created
- ✅ Pull request: Comment updated (선택사항)
5. Save$3
웹훅 핸들러에서 파이프라인 트리거 시 다음 변수를 전달해야 합니다:
| Variable | Description |
|----------|-------------|
|
WEBHOOK_PAYLOAD | 웹훅 페이로드 JSON 문자열 |
| TRIGGER_EVENT | pullrequest:comment_created 또는 pullrequest:comment_updated |Pipeline Examples
$3
`yaml
pipelines:
pull-requests:
'**':
- step:
name: AI Code Review
script:
- curl -fsSL https://bun.sh/install | bash
- export PATH="$HOME/.bun/bin:$PATH"
- npx bitbucket-gemini-action
`$3
`yaml
pipelines:
custom:
security-review:
- step:
name: Security Review
script:
- curl -fsSL https://bun.sh/install | bash
- export PATH="$HOME/.bun/bin:$PATH"
- export MODE="agent"
- export PROMPT="Focus on security: SQL injection, XSS, authentication issues"
- npx bitbucket-gemini-action
`$3
`yaml
definitions:
steps:
- step: &review
name: Review
script:
- npx bitbucket-gemini-actionschedules:
- cron: "0 9 1-5"
pipeline: custom/daily-review
`How It Works
1. Prepare Phase: Parses Bitbucket context, validates triggers, creates tracking comment
2. Execute Phase: Calls Gemini API, processes response, posts comments
`
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ PR Event or │────▶│ Prepare Phase │────▶│ Execute Phase │
│ @gemini Tag │ │ - Parse context│ │ - Call Gemini │
│ │ │ - Validate │ │ - Post comments│
└─────────────────┘ └─────────────────┘ └─────────────────┘
`Project Structure
`
bitbucket-gemini-action/
├── src/
│ ├── bitbucket/ # Bitbucket API integration
│ │ ├── api/ # REST API client
│ │ ├── data/ # Data fetching & formatting
│ │ ├── operations/ # Comment operations
│ │ └── validation/ # Permission & trigger validation
│ ├── gemini/ # Gemini API integration
│ │ ├── client.ts # API client
│ │ ├── prompts.ts # Prompt templates
│ │ └── tools.ts # Function calling tools
│ ├── modes/ # Execution modes
│ │ ├── tag/ # @gemini mention mode
│ │ └── agent/ # Automation mode
│ ├── entrypoints/ # Pipeline entry points
│ │ ├── prepare.ts # Phase 1
│ │ └── execute.ts # Phase 2
│ └── utils/ # Shared utilities
├── examples/ # Pipeline examples
├── bitbucket-pipelines.yml # Main pipeline config
└── package.json
`Security
- Timestamp Filtering: Comments modified after trigger time are ignored
- Bot Detection: Prevents infinite loops from bot comments
- Permission Validation: Verifies actor has write permissions
- Content Sanitization: Removes potential prompt injection attempts
Development
`bash
Install dependencies
bun installType check
bun run typecheckFormat code
bun run formatRun tests
bun test
`Troubleshooting
$3
Ensure
GEMINI_API_KEY or GOOGLE_API_KEY is set in repository variables.$3
Set either:
-
BITBUCKET_ACCESS_TOKEN, or
- Both BITBUCKET_USERNAME and BITBUCKET_APP_PASSWORD$3
The default trigger is
@gemini. Check if you've customized TRIGGER_PHRASE`.1. Ensure the pipeline is triggered by PR events
2. Check that credentials have PR comment permissions
3. Verify the trigger phrase is in the comment
MIT
Inspired by claude-code-action by Anthropic.