Fotógrafo Cheat Sheet
"Clase de la hoja" id="copy-btn" class="copy-btn" onclick="copyAllCommands()" Copiar todos los comandos id="pdf-btn" class="pdf-btn" onclick="generatePDF()" Generar PDF seleccionado/button ■/div titulada
Sinopsis
Sourcegraph es una plataforma de búsqueda y navegación de código universal que ayuda a los desarrolladores a entender, corregir y automatizar los cambios en toda su base de código. Proporciona búsqueda de código semántico, navegación de repositorio cruzado e inteligencia de código para equipos que trabajan con bases de código grandes y distribuidas.
NOVEDAD Nota: Disponible como servicio en la nube (sourcegraph.com) o despliegue autoanfitriono. Tier libre disponible con límites de uso.
Instalación
Servicio Cloud
# Access Sourcegraph Cloud
# Visit: https://sourcegraph.com
# Sign up with GitHub, GitLab, or email
# Connect repositories for indexing
Despliegue autónomo
# 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
Extensiones del navegador
# Chrome/Edge extension
# Visit Chrome Web Store
# Search "Sourcegraph"
# Install browser extension
# Firefox extension
# Visit Firefox Add-ons
# Search "Sourcegraph"
# Install extension
Búsqueda Sintaxis
Búsqueda básica
# Simple text search
hello world
# Case-sensitive search
case:yes Hello World
# Regular expression search
/func\s+\w+\(/
# Exact match
"exact phrase"
Filtros de depósito
# 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
Filtros de archivos
# 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
Filtros de idiomas
# Search in specific language
lang:javascript async function
# Search in multiple languages
| lang:python | go | rust error handling |
# Exclude languages
-lang:test function definition
Filtros de contenido
# 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
Búsqueda avanzada
Búsqueda estructural
# 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]'
Búsqueda basada en el tiempo
# 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
Autor y Commit Filtros
# 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
Operadores booleanos
# 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
Ir a la definición
# 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
Signatura de búsqueda
# 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
Extensión del navegador
Integración GitHub
# 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
Configuración
# Extension settings:
# 1. Click extension icon
# 2. Configure Sourcegraph URL
# 3. Set authentication token
# 4. Enable/disable features
API Usage
API de GraphQL
# 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 Ejemplos
# 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 Herramienta
Instalación
# 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
Autenticación
# 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
Comandos de búsqueda
# 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
Cambios de lotes
Creando cambios de lote
# 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
Gestión de los cambios de lote
# 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
Ejemplos de cambio de lotes
# 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
Control del Código
Configuración de monitores
# 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
Ejemplos de monitor
# 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"
Notificaciones
# Supported notification channels:
# - Email
# - Slack
# - Microsoft Teams
# - Webhook
# - PagerDuty
Code Insights
Creando visiones
# 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"
}
]
}
Seguimiento de la migración
# 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"
}
]
}
Características de la empresa
SAML/SSO Integration
# Configure SAML authentication
# 1. Admin panel > Authentication
# 2. Enable SAML
# 3. Configure identity provider
# 4. Set attribute mappings
# 5. Test authentication
Permisos de depósito
# 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
Auditoría
# 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
Optimización del rendimiento
Resultados de la búsqueda
# Optimize search queries:
# - Use specific repository filters
# - Limit file type searches
# - Use structural search for complex patterns
# - Avoid overly broad regex patterns
Gestión del índice
# 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
Consideraciones de escala
# 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
Solución de problemas
Cuestiones comunes
# 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
Controles de salud
# 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
```_
## Buenas prácticas
### Estrategias de búsqueda
```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
Repository Organization
# Organize repositories logically:
# - Group related repositories
# - Use consistent naming conventions
# - Tag repositories by team/project
# - Set appropriate permissions
Equipo de adopción
# Encourage team usage:
# - Provide training sessions
# - Share useful search patterns
# - Create documentation
# - Set up monitoring for common issues
# - Integrate with existing workflows