Skip to content

Sourcegraph Cheat Sheet

Overview

Sourcegraph is a universal code search and navigation platform that helps developers understand, fix, and automate changes across their entire codebase. It provides semantic code search, cross-repository navigation, and code intelligence for teams working with large, distributed codebases.

⚠️ Note: Available as cloud service (sourcegraph.com) or self-hosted deployment. Free tier available with usage limits.

Installation & Setup

Cloud Service

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

Self-Hosted Deployment

# 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

Browser Extensions

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

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

Search Syntax

# Simple text search
hello world

# Case-sensitive search
case:yes Hello World

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

# Exact match
"exact phrase"

Repository Filters

# 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

File Filters

# 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

Language Filters

# Search in specific language
lang:javascript async function

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

# Exclude languages
-lang:test function definition

Content Filters

# 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

Author and Commit Filters

# 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

Boolean Operators

# AND operator (default)
function AND async

# OR operator
function OR method

# NOT operator
function NOT test

# Grouping with parentheses
(function OR method) AND async

Code Intelligence

Go to Definition

# 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"

Cross-Repository Navigation

# 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

Browser Extension

GitHub Integration

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

GitLab Integration

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

Configuration

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

API Usage

GraphQL API

# API endpoint
https://sourcegraph.com/.api/graphql

# Authentication header
Authorization: token YOUR_ACCESS_TOKEN

Search API

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

Scaling Considerations

# 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

Troubleshooting

Common Issues

# 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

Debug Information

# 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

Health Checks

# 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

Best Practices

Search Strategies

# 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

Repository Organization

# Organize repositories logically:
# - Group related repositories
# - Use consistent naming conventions
# - Tag repositories by team/project
# - Set appropriate permissions

Team Adoption

# Encourage team usage:
# - Provide training sessions
# - Share useful search patterns
# - Create documentation
# - Set up monitoring for common issues
# - Integrate with existing workflows

Resources

Documentation

Community

Training