Sourcegraph Feuille de chaleur
Aperçu général
Sourcegraph est une plateforme universelle de recherche et de navigation de code qui aide les développeurs à comprendre, corriger et automatiser les changements sur toute leur base de code. Il fournit des données de recherche de code sémantique, de navigation croisée et d'intelligence de code pour les équipes travaillant avec de grandes bases de code distribuées.
C'est pas vrai. Note: Disponible en tant que service Cloud (sourcegraph.com) ou déploiement auto-organisé. Niveau gratuit disponible avec limites d'utilisation.
Installation et configuration
Service Cloud
# Access Sourcegraph Cloud
# Visit: https://sourcegraph.com
# Sign up with GitHub, GitLab, or email
# Connect repositories for indexing
Déploiement autonome
# 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
```_
### Extensions du navigateur
```bash
# Chrome/Edge extension
# Visit Chrome Web Store
# Search "Sourcegraph"
# Install browser extension
# Firefox extension
# Visit Firefox Add-ons
# Search "Sourcegraph"
# Install extension
```_
## Recherche Syntaxe
### Recherche fondamentale
```bash
# Simple text search
hello world
# Case-sensitive search
case:yes Hello World
# Regular expression search
/func\s+\w+\(/
# Exact match
"exact phrase"
Filtres de dépôt
# 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
Filtres de fichiers
# 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
Filtres linguistiques
# Search in specific language
lang:javascript async function
# Search in multiple languages
lang:python|go|rust error handling
# Exclude languages
-lang:test function definition
Filtres de contenu
# 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
Recherche avancée
Recherche structurelle
# 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]'
Recherche dans le temps
# 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
Auteur et Commit Filtres
# 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
Opérateurs booléens
# 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 Renseignements
Aller à la définition
# 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"
Navigation entre dépôts
# 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
Recherche de symboles
# 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
Extension du navigateur
Intégration GitHub
# Features on GitHub:
# - Code intelligence on files
# - Go to definition
# - Find references
# - Search across repositories
# - Hover tooltips for symbols
Intégration GitLab
# 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 Utilisation
API GraphQL
# API endpoint
https://sourcegraph.com/.api/graphql
# Authentication header
Authorization: token YOUR_ACCESS_TOKEN
Recherche dans l'API
query SearchQuery($query: String!) {
search(query: $query) {
results {
results {
... on FileMatch {
file {
path
repository {
name
}
}
lineMatches {
lineNumber
line
}
}
}
}
}
}
API de dépôt
query RepositoryQuery($name: String!) {
repository(name: $name) {
name
url
description
defaultBranch {
name
}
commit(rev: "HEAD") {
oid
message
}
}
}
CURL Exemples
# 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 Outil
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
Authentification
# 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
Commandes de recherche
# 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"
Gestion des dépôts
# 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
Changements par lots
Création de changements de lots
# 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
Gestion des changements de lots
# 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
Exemples de changement de lot
# 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
Surveillance du code
Configuration des moniteurs
# 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
Exemples de surveillance
# 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
Perspectives de code
Création de perspectives
# 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"
}
]
}
Suivi des migrations
# 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"
}
]
}
Caractéristiques de l'entreprise
Intégration SAML/SSO
# Configure SAML authentication
# 1. Admin panel > Authentication
# 2. Enable SAML
# 3. Configure identity provider
# 4. Set attribute mappings
# 5. Test authentication
Autorisations de dépôt
# 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
Comptabilisation des audits
# 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
Optimisation des performances
Exécution de la recherche
# Optimize search queries:
# - Use specific repository filters
# - Limit file type searches
# - Use structural search for complex patterns
# - Avoid overly broad regex patterns
Gestion des index
# 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
Élargissement des considérations
# 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
Dépannage
Questions communes
# 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
Renseignements sur les débogueurs
# 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
Contrôles de santé
# 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
Meilleures pratiques
Stratégies de recherche
# 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
Organisme de dépôt
# Organize repositories logically:
# - Group related repositories
# - Use consistent naming conventions
# - Tag repositories by team/project
# - Set appropriate permissions
Adoption par l'équipe
# Encourage team usage:
# - Provide training sessions
# - Share useful search patterns
# - Create documentation
# - Set up monitoring for common issues
# - Integrate with existing workflows
Ressources
Documentation
- [Documentation de la source] (LINK_9)
- Référence de recherche
- [Documentation API] (LINK_9)
Communauté
- [Discorde des sources] (LINK_9)
- [Débats de GitHub] (LINK_9)
- [Forum communautaire] (LINK_9)
Formation
- [Source : Apprendre] (LINK_9)
- [Tutoriels de recherche] (LINK_9)
- [Guide des meilleures pratiques] (LINK_9)