콘텐츠로 이동

Sourcegraph 치트 시트

개요

Sourcegraph는 개발자가 전체 코드베이스에서 변경 사항을 이해하고, 수정하고, 자동화할 수 있도록 돕는 범용 코드 검색 및 탐색 플랫폼입니다. 대규모 분산 코드베이스로 작업하는 팀을 위해 의미론적 코드 검색, 저장소 간 탐색 및 코드 인텔리전스를 제공합니다.

⚠️ 참고: 클라우드 서비스(sourcegraph.com) 또는 자체 호스팅 배포로 사용 가능. 사용 제한이 있는 무료 티어 제공.

설치 및 설정

클라우드 서비스

# Access Sourcegraph Cloud
# Visit: https://sourcegraph.com
# Sign up with GitHub, GitLab, or email
# Connect repositories for indexing

자체 호스팅 배포

# Docker Compose deployment
git clone https://github.com/sourcegraph/deploy-sourcegraph-docker.git
cd deploy-sourcegraph-docker
docker-compose up -d

# Kubernetes deployment
kubectl apply -f https://raw.githubusercontent.com/sourcegraph/deploy-sourcegraph/master/base/sourcegraph.yaml

# Single container (development)
docker run -d \
  --name sourcegraph \
  -p 7080:7080 \
  -v ~/.sourcegraph/config:/etc/sourcegraph \
  -v ~/.sourcegraph/data:/var/opt/sourcegraph \
  sourcegraph/server:latest

브라우저 확장 프로그램

# Chrome/Edge extension
# Visit Chrome Web Store
# Search "Sourcegraph"
# Install browser extension

# Firefox extension
# Visit Firefox Add-ons
# Search "Sourcegraph"
# Install extension

검색 구문

기본 검색

# Simple text search
hello world

# Case-sensitive search
case:yes Hello World

# Regular expression search
/func\s+\w+\(/

# Exact match
"exact phrase"

저장소 필터

# Search in specific repository
repo:github.com/facebook/react useState

# Search in multiple repositories
repo:facebook/react|vue/vue useState

# Exclude repositories
-repo:test-repo main function

# Search by repository pattern
repo:.*-frontend$ component

파일 필터

# Search in specific file types
file:\.js$ function

# Search in specific files
file:package.json dependencies

# Exclude file types
-file:\.test\.js$ function

# Search in file paths
file:src/components/ useState

언어 필터

# Search in specific language
lang:javascript async function

# Search in multiple languages
lang:python|go|rust error handling

# Exclude languages
-lang:test function definition

콘텐츠 필터

# Search function definitions
type:symbol function_name

# Search for commits
type:commit bug fix

# Search for diffs
type:diff added new feature

# Search symbols only
type:symbol class MyClass

고급 검색

구조적 검색

# Find function calls with patterns
:[func](:[args])

# Find if statements
if (:[condition]) { :[body] }

# Find class definitions
class :[name] extends :[parent] { :[body] }

# Find import statements
import :[imports] from ':[module]'

시간 기반 검색

# Search commits after date
type:commit after:"2024-01-01" security fix

# Search commits before date
type:commit before:"2024-12-31" refactor

# Search commits in date range
type:commit after:"2024-01-01" before:"2024-06-30" feature

작성자 및 커밋 필터

# Search by commit author
type:commit author:john.doe bug fix

# Search by committer
type:commit committer:jane.smith merge

# Search commit messages
type:commit message:"breaking change"

# Search by commit hash
type:commit 7f8a9b2c

불리언 연산자

# AND operator (default)
function AND async

# OR operator
function OR method

# NOT operator
function NOT test

# Grouping with parentheses
(function OR method) AND async

코드 인텔리전스

정의로 이동

# Navigate to symbol definition
# Click on symbol in code view
# Or use Ctrl+Click (with browser extension)

# Find all references
# Right-click on symbol
# Select "Find references"

저장소 간 탐색

# Find implementations across repos
# Search for interface or abstract class
# View implementations in different repositories

# Trace dependencies
# Click on import statements
# Navigate to source in external repositories

심볼 검색

# Find symbol definitions
type:symbol MyClass

# Find symbols by type
type:symbol function getUserData

# Find symbols in specific repository
repo:myorg/myrepo type:symbol ApiClient

브라우저 확장 프로그램

GitHub 통합

# Features on GitHub:
# - Code intelligence on files
# - Go to definition
# - Find references
# - Search across repositories
# - Hover tooltips for symbols

GitLab 통합

# Features on GitLab:
# - Code navigation
# - Symbol definitions
# - Cross-repository search
# - Merge request code intelligence

구성

# Extension settings:
# 1. Click extension icon
# 2. Configure Sourcegraph URL
# 3. Set authentication token
# 4. Enable/disable features

API 사용

GraphQL API

Would you like me to continue with the remaining sections?```bash

API endpoint

https://sourcegraph.com/.api/graphql

Authentication header

Authorization: token YOUR_ACCESS_TOKEN


### Search API
```graphql
query SearchQuery($query: String!) {
  search(query: $query) {
    results {
      results {
        ... on FileMatch {
          file {
            path
            repository {
              name
            }
          }
          lineMatches {
            lineNumber
            line
          }
        }
      }
    }
  }
}

Repository API

query RepositoryQuery($name: String!) {
  repository(name: $name) {
    name
    url
    description
    defaultBranch {
      name
    }
    commit(rev: "HEAD") {
      oid
      message
    }
  }
}

cURL Examples

# Search repositories
curl -X POST \
  -H "Authorization: token YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query": "query { search(query: \"repo:myorg/myrepo function\") { results { results { __typename } } } }"}' \
  https://sourcegraph.com/.api/graphql

# Get repository information
curl -X POST \
  -H "Authorization: token YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query": "query { repository(name: \"github.com/facebook/react\") { name description } }"}' \
  https://sourcegraph.com/.api/graphql

CLI Tool

Installation

# Install Sourcegraph CLI
# macOS
brew install sourcegraph/src-cli/src-cli

# Linux
curl -L https://github.com/sourcegraph/src-cli/releases/download/3.43.2/src-cli_3.43.2_linux_amd64.tar.gz | tar xz
sudo mv src /usr/local/bin/

# Windows
# Download from GitHub releases
# Add to PATH

Authentication

# Configure CLI
src login https://sourcegraph.com

# Set access token
src config set endpoint https://sourcegraph.com
src config set access-token YOUR_ACCESS_TOKEN

# Verify configuration
src config get

Search Commands

# Basic search
src search "function useState"

# Search with filters
src search "repo:facebook/react useState"

# Output as JSON
src search -json "async function"

# Search with context
src search -context 3 "error handling"

Repository Management

# List repositories
src repos list

# Add repository
src repos add github.com/myorg/myrepo

# Remove repository
src repos remove github.com/myorg/myrepo

# Sync repository
src repos sync github.com/myorg/myrepo

Batch Changes

Creating Batch Changes

# Create batch change spec
cat > batch-change.yaml << EOF
name: update-dependencies
description: Update package.json dependencies
on:
  - repositoriesMatchingQuery: file:package.json
steps:
  - run: npm update
    container: node:16
  - run: npm audit fix
    container: node:16
changesetTemplate:
  title: Update npm dependencies
  body: |
    This batch change updates npm dependencies to their latest versions
    and fixes security vulnerabilities.
  branch: update-dependencies
  commit:
    message: Update npm dependencies and fix security issues
  published: false
EOF

# Apply batch change
src batch apply -f batch-change.yaml

Managing Batch Changes

# List batch changes
src batch list

# Preview batch change
src batch preview -f batch-change.yaml

# Apply batch change
src batch apply -f batch-change.yaml

# Close batch change
src batch close BATCH_CHANGE_ID

Batch Change Examples

# Update copyright headers
name: update-copyright
description: Update copyright year in all files
on:
  - repositoriesMatchingQuery: file:\.js$ OR file:\.py$ OR file:\.go$
steps:
  - run: |
      find . -name "*.js" -o -name "*.py" -o -name "*.go" | \
      xargs sed -i 's/Copyright 2023/Copyright 2024/g'
    container: alpine:latest
changesetTemplate:
  title: Update copyright year to 2024
  body: Automated update of copyright year from 2023 to 2024
  branch: update-copyright-2024
  commit:
    message: Update copyright year to 2024

Code Monitoring

Setting Up Monitors

# Create code monitor
# 1. Go to Sourcegraph web interface
# 2. Navigate to Code Monitoring
# 3. Click "Create monitor"
# 4. Define search query
# 5. Set notification preferences

Monitor Examples

# Monitor for security vulnerabilities
query: "TODO.*security|FIXME.*vulnerability"
description: "Track security-related TODOs and FIXMEs"

# Monitor for deprecated API usage
query: "deprecated.*api|legacy.*function"
description: "Track usage of deprecated APIs"

# Monitor for performance issues
query: "slow.*query|performance.*issue"
description: "Track performance-related comments"

Notifications

# Supported notification channels:
# - Email
# - Slack
# - Microsoft Teams
# - Webhook
# - PagerDuty

Code Insights

Creating Insights

# Language distribution insight
{
  "title": "Language Distribution",
  "type": "lang-stats",
  "repositories": ["github.com/myorg/myrepo"],
  "series": [
    {
      "name": "JavaScript",
      "query": "lang:javascript",
      "stroke": "#f1e05a"
    },
    {
      "name": "Python", 
      "query": "lang:python",
      "stroke": "#3572A5"
    }
  ]
}

Migration Tracking

# Track migration progress
{
  "title": "React Class to Hooks Migration",
  "type": "search-based",
  "repositories": ["github.com/myorg/frontend"],
  "series": [
    {
      "name": "Class Components",
      "query": "class.*extends.*Component",
      "stroke": "#ff0000"
    },
    {
      "name": "Functional Components",
      "query": "const.*=.*\\(.*\\).*=>|function.*\\(",
      "stroke": "#00ff00"
    }
  ]
}

Enterprise Features

SAML/SSO Integration

# Configure SAML authentication
# 1. Admin panel > Authentication
# 2. Enable SAML
# 3. Configure identity provider
# 4. Set attribute mappings
# 5. Test authentication

Repository Permissions

# Sync permissions from code host
# GitHub: Uses repository visibility and team permissions
# GitLab: Uses project visibility and group permissions
# Bitbucket: Uses repository permissions

# Manual permission configuration
# Admin panel > Repositories > Permissions
# Set user/team access levels

Audit Logging

# Enable audit logging
# Admin panel > Audit log
# Configure log retention
# Export logs for compliance

# Log events include:
# - User authentication
# - Repository access
# - Search queries
# - Configuration changes

Performance Optimization

Search Performance

# Optimize search queries:
# - Use specific repository filters
# - Limit file type searches
# - Use structural search for complex patterns
# - Avoid overly broad regex patterns

Index Management

# Repository indexing status
# Admin panel > Repositories
# View indexing progress
# Force re-indexing if needed

# Index configuration
# Adjust indexing frequency
# Set resource limits
# Configure language servers
```### 확장성 고려사항
```bash
# Horizontal scaling:
# - Multiple frontend instances
# - Separate search backend
# - Distributed indexing
# - Load balancing

# Resource requirements:
# - CPU: 4+ cores per 1000 repositories
# - Memory: 8GB+ per instance
# - Storage: SSD recommended for indexes
```## 문제 해결
```bash
# Search not returning results:
# 1. Check repository indexing status
# 2. Verify search syntax
# 3. Check repository permissions
# 4. Review filter settings

# Slow search performance:
# 1. Use more specific queries
# 2. Add repository filters
# 3. Check system resources
# 4. Review index health
```### 일반적인 문제들
```bash
# Enable debug logging
# Admin panel > Monitoring
# Set log level to debug
# Check application logs

# Search debug info
# Add &trace=1 to search URL
# View query execution details
# Analyze performance metrics
```### 디버그 정보
```bash
# System health endpoints
curl https://sourcegraph.com/-/healthz

# Repository sync status
curl https://sourcegraph.com/-/debug/repos

# Search backend status
curl https://sourcegraph.com/-/debug/search
```### 상태 확인
```bash
# Start broad, then narrow:
# 1. Begin with general terms
# 2. Add repository filters
# 3. Refine with file types
# 4. Use structural search for precision

# Use appropriate search types:
# - Text search for general queries
# - Symbol search for definitions
# - Structural search for patterns
# - Commit search for history
```## 모범 사례
```bash
# Organize repositories logically:
# - Group related repositories
# - Use consistent naming conventions
# - Tag repositories by team/project
# - Set appropriate permissions
```### 검색 전략
```bash
# Encourage team usage:
# - Provide training sessions
# - Share useful search patterns
# - Create documentation
# - Set up monitoring for common issues
# - Integrate with existing workflows
```### 저장소 구성
https://docs.sourcegraph.com/##

# 팀 도입
https://docs.sourcegraph.com/code_search/reference#

# 리소스
https://docs.sourcegraph.com/api/graphql##

# 문서
- [Sourcegraph 문서](https://discord.gg/sourcegraph)
- [검색 참조](https://github.com/sourcegraph/sourcegraph/discussions)
- [API 문서](https://community.sourcegraph.com/)
https://learn.sourcegraph.com/##

# 커뮤니티
- [Sourcegraph Discord](https://docs.sourcegraph.com/code_search/tutorials)
- [GitHub 토론](https://docs.sourcegraph.com/admin/how-to)
- [커뮤니티 포럼](