GitHub Copilot 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
GitHub Copilot es una herramienta de terminación de código impulsada por IA desarrollada por GitHub y OpenAI. Proporciona sugerencias de código inteligente, genera funciones enteras y ayuda con documentación y pruebas. Copilot integra perfectamente con IDE populares y admite docenas de lenguajes de programación.
NOVEDAD Nota: Requiere la suscripción a GitHub Copilot (10 por mes, $19 por mes)
Instalación
VS Code
# Install via VS Code Extensions
# Search for "GitHub Copilot" in Extensions marketplace
# Or install via command line
code --install-extension GitHub.copilot
code --install-extension GitHub.copilot-chat
JetBrains IDEs
# Install via JetBrains Plugin Repository
# Go to File > Settings > Plugins
# Search for "GitHub Copilot" and install
Neovim
# Install via plugin manager (e.g., vim-plug)
Plug 'github/copilot.vim'
# Or using packer.nvim
use 'github/copilot.vim'
Autenticación
Configuración inicial
# Authenticate with GitHub account
:Copilot setup
# Check authentication status
:Copilot status
# Sign out
:Copilot signout
Uso básico
Código
// Type function signature and let Copilot suggest implementation
function calculateTax(income, rate) \\\\{
// Copilot will suggest: return income * rate;
\\\\}
// Start typing comment to get function suggestion
// Calculate fibonacci sequence
// Copilot will suggest complete function
Comandos de Chat Copilot
# Open Copilot Chat
Ctrl+Shift+I (VS Code)
# Quick chat
Ctrl+I (VS Code)
# Explain selected code
/explain
# Fix selected code
/fix
# Generate tests
/tests
# Generate documentation
/doc
Atajos de teclado
Shortcut | Action | IDE |
---|---|---|
Tab |
Accept suggestion | All |
Ctrl+] |
Next suggestion | VS Code |
Ctrl+[ |
Previous suggestion | VS Code |
Esc |
Dismiss suggestion | All |
Ctrl+Enter |
Open suggestions panel | VS Code |
Ctrl+Shift+I |
Open Copilot Chat | VS Code |
Ctrl+I |
Quick chat | VS Code |
Alt+] |
Next suggestion | JetBrains |
Alt+[ |
Previous suggestion | JetBrains |
Características avanzadas
GitHub Copilot Chat
# Explain code functionality
/explain What does this function do?
# Fix bugs in selected code
/fix This function has a memory leak
# Generate unit tests
/tests Create comprehensive tests for this class
# Optimize performance
/optimize Make this algorithm more efficient
# Generate documentation
/doc Create JSDoc comments for this function
# Refactor code
/refactor Extract this into smaller functions
Espacio de trabajo de copiloto
# Create issue-to-PR workflow
# 1. Assign GitHub issue to Copilot Workspace
# 2. Copilot analyzes requirements
# 3. Generates implementation plan
# 4. Creates code across multiple files
# 5. Submits pull request for review
Optimización del contexto
// Provide clear context in comments
/**
* User authentication service for e-commerce platform
* Handles login, logout, and session management
* Uses JWT tokens and Redis for session storage
*/
class AuthService \\\\{
// Copilot will generate contextually appropriate methods
\\\\}
// Use descriptive variable names
const userAuthenticationToken = // Copilot suggests JWT implementation
const databaseConnectionPool = // Copilot suggests database setup
Consejos de idiomas
JavaScript/TypeScript
// Interface definitions help Copilot understand structure
interface User \\\\{
id: string;
email: string;
preferences: UserPreferences;
\\\\}
// Copilot will suggest type-safe implementations
function updateUser(user: User) \\\\{
// Suggestions will respect TypeScript types
\\\\}
Python
# Type hints improve suggestions
from typing import List, Dict, Optional
def process_data(items: List[Dict[str, Any]]) -> Optional[Dict[str, int]]:
# Copilot provides type-aware suggestions
pass
# Docstrings provide context
def calculate_metrics(data):
"""
Calculate performance metrics for machine learning model
Args:
data: Training data with features and labels
Returns:
Dictionary with accuracy, precision, recall metrics
"""
# Copilot suggests ML-specific implementations
React/JSX
// Component props help Copilot understand structure
interface ButtonProps \\\\{
variant: 'primary'|'secondary';
size: 'small'|'medium'|'large';
onClick: () => void;
\\\\}
// Copilot suggests complete component implementation
const Button: React.FC<ButtonProps> = (\\\\{ variant, size, onClick \\\\}) => \\\\{
// Suggestions include proper JSX and styling
\\\\};
Buenas prácticas
Effective Prompting
// ❌ Vague context
function process() \\\\{
// Limited suggestions
\\\\}
// ✅ Clear context
/**
* Process e-commerce order data
* Validate payment, update inventory, send confirmation email
*/
function processOrder(order, paymentMethod, inventory) \\\\{
// Rich, contextual suggestions
\\\\}
Code Review Integration
# Use Copilot for code review assistance
# 1. Select code block
# 2. Ask Copilot to review for:
# - Security vulnerabilities
# - Performance issues
# - Code style consistency
# - Potential bugs
# Example review prompts
/explain potential security issues in this code
/fix performance bottlenecks in this function
/optimize this database query
Pruebas con Copilot
// Generate comprehensive test suites
// 1. Select function or class
// 2. Use /tests command
// 3. Copilot generates:
// - Unit tests
// - Edge cases
// - Mock implementations
// - Test data
// Example test generation
describe('UserService', () => \\\\{
// Copilot suggests complete test suite
it('should authenticate valid user', () => \\\\{
// Test implementation suggestions
\\\\});
\\\\});
Configuración
VS Code Settings
\\\\{
"github.copilot.enable": \\\\{
"*": true,
"yaml": false,
"plaintext": false
\\\\},
"github.copilot.advanced": \\\\{
"secret_key": "example",
"length": 500
\\\\},
"github.copilot.chat.localeOverride": "en"
\\\\}
Configuración Neovim
-- Copilot configuration
vim.g.copilot_no_tab_map = true
vim.g.copilot_assume_mapped = true
vim.g.copilot_tab_fallback = ""
-- Custom keybindings
vim.api.nvim_set_keymap("i", "<C-J>", 'copilot#Accept("<CR>")', \\\\{ silent = true, expr = true \\\\})
vim.api.nvim_set_keymap("i", "<C-H>", 'copilot#Previous()', \\\\{ silent = true, expr = true \\\\})
vim.api.nvim_set_keymap("i", "<C-L>", 'copilot#Next()', \\\\{ silent = true, expr = true \\\\})
Solución de problemas
Cuestiones comunes
# Copilot not working
:Copilot status
# Check authentication and network connectivity
# No suggestions appearing
# 1. Check file type is supported
# 2. Verify Copilot is enabled for file type
# 3. Restart IDE
# 4. Check subscription status
# Suggestions are poor quality
# 1. Provide more context in comments
# 2. Use descriptive variable names
# 3. Include type annotations
# 4. Add relevant imports and dependencies
Optimización del rendimiento
# Reduce latency
# 1. Use local caching
# 2. Optimize network connection
# 3. Close unnecessary files
# 4. Restart IDE periodically
# Improve suggestion quality
# 1. Keep related files open
# 2. Use consistent coding style
# 3. Include comprehensive comments
# 4. Maintain clean project structure
Características de la empresa
GitHub Copilot Business
# Organization management
# 1. Admin controls for user access
# 2. Usage analytics and reporting
# 3. Policy enforcement
# 4. Audit logs
# Security features
# 1. Code suggestion filtering
# 2. IP allowlisting
# 3. SAML SSO integration
# 4. Data residency controls
Compliance and Security
# Data handling
# 1. Code snippets not stored by default
# 2. Telemetry can be disabled
# 3. On-premises deployment options
# 4. GDPR and SOC 2 compliance
# Content filtering
# 1. Block suggestions matching public code
# 2. Filter sensitive patterns
# 3. Customize blocked content
# 4. Audit suggestion sources
Ejemplos de integración
CI/CD Pipeline
# GitHub Actions with Copilot
name: Copilot Code Review
on: [pull_request]
jobs:
copilot-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Copilot Code Analysis
uses: github/copilot-cli-action@v1
with:
command: 'review'
files: '**/*.js'
Flujos de trabajo personalizados
// Automated documentation generation
// 1. Select functions without documentation
// 2. Use Copilot to generate JSDoc comments
// 3. Review and commit documentation updates
// Code migration assistance
// 1. Provide target framework context
// 2. Use Copilot to suggest migration patterns
// 3. Iteratively convert code sections
// 4. Test and validate migrations