Master Git workflows directly from your code editor for efficient version control
Master Git workflows directly from your code editor for efficient version control
The Source Control panel in modern IDEs provides a visual interface for Git operations, making version control more accessible and intuitive.
VS Code Source Control Panel Overview:
1┌─────────────────────────────────────┐
2│ SOURCE CONTROL ... │
3├─────────────────────────────────────┤
4│ Message: Add user authentication │
5│ ✓ Commit ▼ │
6├─────────────────────────────────────┤
7│ CHANGES (5) + │
8│ ▸ M src/auth.ts │
9│ ▸ M src/user.ts │
10│ ▸ A src/middleware/auth.ts │
11│ ▸ D src/old-auth.ts │
12│ ▸ ?? src/types/auth.d.ts │
13├─────────────────────────────────────┤
14│ STAGED CHANGES (2) - │
15│ ▸ M README.md │
16│ ▸ M package.json │
17└─────────────────────────────────────┘
18
19Legend:
20M = Modified
21A = Added (new file)
22D = Deleted
23?? = Untracked
24U = Unmerged (conflict)Basic Git Workflow in VS Code:
1// 1. Make changes to files
2function authenticateUser(username, password) {
3 // New authentication logic
4 const user = await validateCredentials(username, password);
5 return generateToken(user);
6}
7
8// 2. View changes in Source Control panel
9// - File appears under "CHANGES"
10// - Click file to see diff
11
12// 3. Stage changes
13// - Click + icon next to file
14// - Or stage all: + icon in CHANGES header
15// - File moves to "STAGED CHANGES"
16
17// 4. Write commit message
18// - Type message in input box at top
19// - First line: Brief summary (50 chars)
20// - Blank line
21// - Detailed description
22
23// 5. Commit
24// - Click ✓ Commit button
25// - Or Ctrl+Enter (Cmd+Enter on Mac)
26
27// 6. Push to remote
28// - Click ... menu → Push
29// - Or sync button in status barFile Status Indicators:
1// In VS Code editor tabs and file explorer:
2
3// src/auth.ts (M) - Modified file
4// ├─ Dot indicator next to filename
5// ├─ Shows in Source Control → Changes
6// └─ Can view diff by clicking
7
8// src/new-feature.ts (??) - Untracked file
9// ├─ Marked as untracked
10// ├─ Not tracked by Git yet
11// └─ Need to stage and commit
12
13// src/config.ts (D) - Deleted file
14// ├─ Strikethrough or special indicator
15// ├─ Shows in Changes as deleted
16// └─ Needs to be staged and committed
17
18// src/conflict.ts (U) - Merge conflict
19// ├─ Warning indicator
20// ├─ Shows conflict markers in editor
21// └─ Requires manual resolutionViewing Changes (Diff View):
1// Click any changed file to open diff view
2
3// Left side: Old version (before changes)
4function getUser(id) {
5 return database.users.find(id);
6}
7
8// Right side: New version (current changes)
9function getUser(id: number): User | null {
10 const user = database.users.find(id);
11 if (!user) {
12 throw new Error(`User ${id} not found`);
13 }
14 return user;
15}
16
17// Visual indicators:
18// - Red background: Removed lines
19// - Green background: Added lines
20// - Modified lines show both colorsStaging Strategies:
1// Strategy 1: Stage entire files
2// Good for: Complete features in single files
3// Click + next to each file
4
5// Strategy 2: Stage specific lines (Partial staging)
6// Good for: Multiple unrelated changes in one file
7// 1. Open diff view
8// 2. Select lines to stage
9// 3. Right-click → Stage Selected Ranges
10
11// Example: Only stage the type annotation
12function processData(data: string) { // ← Stage only this line
13 const result = transform(data);
14 console.log('Debug:', result); // ← Don't stage debug code
15 return result;
16}
17
18// Strategy 3: Stage all changes
19// Good for: Batch commits, end of work session
20// Click + in CHANGES header
21// Or Ctrl+Shift+G → Stage All Changes
22
23// Strategy 4: Interactive staging
24// Use Git Graph extension for visual stagingCommit Message Best Practices:
1✅ Good commit messages:
2feat: Add user authentication with JWT
3fix: Resolve memory leak in cache invalidation
4refactor: Extract validation logic to separate module
5docs: Update API documentation for v2 endpoints
6
7❌ Bad commit messages:
8fixed stuff
9update
10asdf
11WIPSource Control Panel Keyboard Shortcuts:
1Ctrl+Shift+G (Cmd+Shift+G) - Open Source Control panel
2Ctrl+Enter (Cmd+Enter) - Commit staged changes
3Ctrl+K Ctrl+U - Unstage all changes
4Ctrl+K Ctrl+D - View diff of selected fileStatus Bar Git Integration:
1┌────────────────────────────────────────────┐
2│ main* ↓1 ↑2 ⚠️ 2 🐛 0 Ln 45 │
3└────────────────────────────────────────────┘
4 │ │ │ │ │
5 │ │ │ └─ Errors └─ Line number
6 │ │ └─ Warnings
7 │ └─ Sync status (1 behind, 2 ahead)
8 └─ Current branch (* = uncommitted changes)
9
10// Click branch name to:
11// - Switch branches
12// - Create new branch
13// - View all branchesManaging branches visually in your IDE makes complex Git workflows simple and intuitive.
Creating Branches in VS Code:
1// Method 1: Click branch name in status bar
2// Status bar: "main" → Click → "Create new branch"
3
4// Method 2: Command Palette
5// Ctrl+Shift+P → "Git: Create Branch"
6
7// Method 3: Source Control panel
8// ... menu → Branch → Create Branch
9
10// Example workflow:
11// Currently on: main
12// Create branch: feature/user-profile
13// → Automatically switches to new branch
14// → Start coding immediately
15
16function createUserProfile(data) {
17 // New feature development on feature branch
18 return {
19 ...data,
20 createdAt: new Date(),
21 status: 'active'
22 };
23}Branch Naming Conventions:
1# Feature branches
2feature/user-authentication
3feature/payment-integration
4feature/dark-mode
5
6# Bug fix branches
7fix/memory-leak
8fix/login-error
9bugfix/api-timeout
10
11# Hotfix branches (urgent production fixes)
12hotfix/security-patch
13hotfix/critical-bug
14
15# Release branches
16release/v1.2.0
17release/2024-01
18
19# Experimental branches
20experiment/new-architecture
21spike/performance-testSwitching Branches:
1// Current branch: main
2// Working on: src/feature.ts (uncommitted changes)
3
4// Scenario 1: Clean working directory
5// → Click branch name → Select branch
6// → Instant switch ✅
7
8// Scenario 2: Uncommitted changes
9// → Try to switch branches
10// → VS Code warns: "You have uncommitted changes"
11
12// Options:
13// 1. Commit changes first
14git commit -m "WIP: Feature in progress"
15
16// 2. Stash changes (save for later)
17// Command Palette → "Git: Stash"
18// → Changes saved temporarily
19// → Switch branches
20// → Come back later: "Git: Apply Stash"
21
22// 3. Discard changes (careful!)
23// Right-click file → Discard Changes
24
25// Example: Stash workflow
26// On feature/new-ui
27const newDesign = {
28 theme: 'dark',
29 layout: 'modern'
30}; // ← Uncommitted
31
32// Emergency: Need to fix bug on main
33// 1. Stash changes: Ctrl+Shift+P → "Git: Stash"
34// 2. Switch to main
35// 3. Fix bug and commit
36// 4. Switch back to feature/new-ui
37// 5. Apply stash: Ctrl+Shift+P → "Git: Pop Stash"
38// → newDesign code reappears ✅Branch Management in Source Control:
1┌─────────────────────────────────────┐
2│ SOURCE CONTROL ≡ ... │
3│ │
4│ BRANCHES │
5│ ▸ main (current) │
6│ ▸ feature/user-auth │
7│ ▸ feature/payment │
8│ ▸ fix/login-bug │
9│ │
10│ REMOTES │
11│ ▸ origin/main │
12│ ▸ origin/feature/user-auth │
13│ ▸ origin/develop │
14└─────────────────────────────────────┘
15
16// Right-click any branch for options:
17// - Checkout (switch to)
18// - Delete branch
19// - Rename branch
20// - Merge into current branch
21// - Rebase current branch onto...
22// - Compare with current branchBranch Comparison and Diff:
1// Compare branches to see what changed
2
3// Method 1: Git Graph extension
4// Shows visual branch history
5// Click any branch to compare
6
7// Method 2: Command Palette
8// "Git: Compare with Branch"
9// Select branch to compare
10
11// Example: Compare feature branch with main
12// feature/user-auth vs main
13
14// Files changed:
15// + src/auth/jwt.ts (new file)
16// + src/auth/middleware.ts (new file)
17// M src/routes/user.ts (modified)
18// M package.json (modified)
19
20// Click any file to see exact changesMerging Branches:
1// Scenario: Merge feature into main
2
3// 1. Switch to target branch (main)
4// Click "main" in status bar
5
6// 2. Merge feature branch
7// Command Palette → "Git: Merge Branch"
8// Select: feature/user-auth
9
10// 3. If no conflicts:
11// → Merge completes automatically ✅
12// → Changes from feature branch now in main
13
14// 4. If conflicts exist:
15// → VS Code shows conflict markers
16// → Resolve conflicts (covered in next section)
17
18// Example merge result:
19// Before merge (main):
20function getUser(id) {
21 return users.find(id);
22}
23
24// Feature branch added authentication:
25function getUser(id) {
26 if (!isAuthenticated()) {
27 throw new Error('Not authenticated');
28 }
29 return users.find(id);
30}
31
32// After merge: main has authentication ✅Deleting Branches:
1# After merging feature branch into main
2
3# Method 1: Source Control panel
4# Right-click branch → Delete Branch
5
6# Method 2: Command Palette
7# "Git: Delete Branch"
8# Select branch to delete
9
10# VS Code warnings:
11# ⚠️ "Branch has unmerged changes" → Don't delete yet
12# ✅ "Branch is fully merged" → Safe to delete
13
14# Delete both local and remote:
15# 1. Delete local: Right-click → Delete Branch
16# 2. Delete remote: Right-click → Delete Remote BranchGitLens Extension - Enhanced Branch Features:
1// GitLens adds powerful branch visualization
2
3// Branch comparison view:
4// - See all commits between branches
5// - View file changes
6// - Compare any two branches
7// - Cherry-pick commits
8
9// Timeline view:
10// - Visual branch history
11// - See when branches diverged
12// - Identify merge points
13// - Track feature development
14
15// Commit graph:
16main ●─────●─────●─────●
17 ╲ ╱
18feature ●─────●─────●Merge conflicts are inevitable in collaborative development. Visual tools in modern IDEs make conflict resolution straightforward and safe.
Understanding Merge Conflicts:
1// Scenario: Two developers modify same file
2
3// Developer A (on main):
4function calculateTotal(items) {
5 const subtotal = items.reduce((sum, item) => sum + item.price, 0);
6 const tax = subtotal * 0.08;
7 return subtotal + tax;
8}
9
10// Developer B (on feature branch):
11function calculateTotal(items) {
12 const subtotal = items.reduce((sum, item) => sum + item.price, 0);
13 const tax = subtotal * 0.10; // Different tax rate!
14 const shipping = 5.99; // Added shipping!
15 return subtotal + tax + shipping;
16}
17
18// When merging: CONFLICT!
19// Both changed the same linesConflict Markers in Code:
1function calculateTotal(items) {
2 const subtotal = items.reduce((sum, item) => sum + item.price, 0);
3
4<<<<<<< HEAD (Current Change - main branch)
5 const tax = subtotal * 0.08;
6 return subtotal + tax;
7=======
8 const tax = subtotal * 0.10;
9 const shipping = 5.99;
10 return subtotal + tax + shipping;
11>>>>>>> feature/update-pricing (Incoming Change)
12}
13
14// Conflict markers explained:
15// <<<<<<< HEAD - Start of current branch changes
16// Current branch code
17// ======= - Separator
18// Incoming branch code
19// >>>>>>> branch-name - End of incoming branch changesVS Code Conflict Resolution UI:
1// When conflict detected, VS Code shows:
2
3function calculateTotal(items) {
4 const subtotal = items.reduce((sum, item) => sum + item.price, 0);
5
6 // ┌─────────────────────────────────────────┐
7 // │ Accept Current Change │
8 // │ Accept Incoming Change │
9 // │ Accept Both Changes │
10 // │ Compare Changes │
11 // └─────────────────────────────────────────┘
12
13<<<<<<< HEAD
14 const tax = subtotal * 0.08;
15 return subtotal + tax;
16||||||| merged common ancestors
17 const tax = subtotal * 0.05;
18 return subtotal + tax;
19=======
20 const tax = subtotal * 0.10;
21 const shipping = 5.99;
22 return subtotal + tax + shipping;
23>>>>>>> feature/update-pricing
24
25 // Click options above conflict:
26 // 1. "Accept Current Change" → Keep main version
27 // 2. "Accept Incoming Change" → Use feature branch version
28 // 3. "Accept Both Changes" → Keep both (if makes sense)
29 // 4. "Compare Changes" → Open 3-way merge editor
30}3-Way Merge Editor:
1┌────────────────────────────────────────────────────────┐
2│ CURRENT (main) │ RESULT │ INCOMING │
3│ │ │ (feature) │
4├────────────────────────────────────────────────────────┤
5│ const tax = │ const tax = │ const tax = │
6│ subtotal * 0.08; │ subtotal * │ subtotal * │
7│ return subtotal │ 0.10; │ 0.10; │
8│ + tax; │ const ship... │ const shipping │
9│ │ return ... │ = 5.99; │
10│ [Accept] │ │ [Accept] │
11│ │ ↓ Apply │ │
12└────────────────────────────────────────────────────────┘
13
14// How to use:
15// 1. Review changes in left (current) and right (incoming)
16// 2. Click checkboxes to select which changes to keep
17// 3. Edit result in center panel if needed
18// 4. Click "Complete Merge" when satisfiedResolving Conflicts Manually:
1// Option 1: Accept one side completely
2// → Click "Accept Current Change" or "Accept Incoming Change"
3
4// Option 2: Manual resolution (recommended for complex conflicts)
5// Delete conflict markers and write the correct code:
6
7function calculateTotal(items) {
8 const subtotal = items.reduce((sum, item) => sum + item.price, 0);
9
10 // ✅ Manually resolved: Best of both
11 const TAX_RATE = 0.10; // Use new rate from feature branch
12 const tax = subtotal * TAX_RATE;
13 const shipping = 5.99; // Keep new shipping from feature
14
15 return subtotal + tax + shipping; // Combine both changes
16}
17
18// Remove all conflict markers:
19// - Delete <<<<<<< HEAD
20// - Delete =======
21// - Delete >>>>>>> branch-name
22// - Keep only the final, correct codeConflict Resolution Workflow:
1// Step-by-step conflict resolution
2
3// 1. Attempt merge
4// Command Palette → "Git: Merge Branch"
5// Select feature branch
6
7// 2. VS Code shows conflicts
8// Files with conflicts appear in Source Control panel
9// Marked with "U" (unmerged) status
10
11// 3. Open conflicted file
12// Click file in Source Control
13// See conflict markers and resolution options
14
15// 4. Resolve each conflict
16// For each conflict section:
17// a. Understand both changes
18// b. Choose resolution strategy
19// c. Edit code as needed
20// d. Remove conflict markers
21
22// 5. Mark as resolved
23// After fixing all conflicts in file:
24// - Stage the file (click + icon)
25// - This marks it as resolved
26
27// 6. Complete the merge
28// After resolving all conflicted files:
29// - All files should be staged
30// - Commit message auto-populated
31// - Click Commit button
32
33// 7. Verify the merge
34// Test the merged code
35// Ensure nothing broke
36// Push to remote if all good
37
38// Example: Complex conflict resolution
39class UserService {
40<<<<<<< HEAD
41 async getUser(id) {
42 const user = await db.users.findById(id);
43 return user;
44 }
45=======
46 async getUser(id) {
47 const cached = cache.get(id);
48 if (cached) return cached;
49
50 const user = await db.users.findById(id);
51 cache.set(id, user);
52 return user;
53 }
54>>>>>>> feature/add-caching
55}
56
57// ✅ Resolution: Keep caching but add error handling
58class UserService {
59 async getUser(id) {
60 // Check cache first
61 const cached = cache.get(id);
62 if (cached) return cached;
63
64 // Fetch from database
65 const user = await db.users.findById(id);
66
67 // Handle not found case (from main branch)
68 if (!user) {
69 throw new Error(`User ${id} not found`);
70 }
71
72 // Cache the result
73 cache.set(id, user);
74 return user;
75 }
76}Aborting a Merge:
1// If conflicts are too complex or you made a mistake:
2
3// Method 1: Command Palette
4// "Git: Abort Merge"
5// → Returns to state before merge
6// → All conflict markers removed
7// → No changes committed
8
9// Method 2: Source Control panel
10// ... menu → Abort Merge
11
12// ⚠️ Warning: This discards all conflict resolution work
13// Use only if you want to start overAdvanced Conflict Tools:
1// GitLens extension features:
2
3// 1. Inline blame during conflicts
4// See who made each conflicting change
5// Understand context behind changes
6
7// 2. Conflict navigation
8// Jump to next/previous conflict
9// Keyboard shortcuts for quick resolution
10
11// 3. Side-by-side comparison
12// See full file context
13// Not just conflicted lines
14
15// 4. Auto-resolution hints
16// Suggests resolution based on patterns
17// Learns from your past resolutions
18
19// Example: Using inline blame
20function processOrder(order) {
21<<<<<<< HEAD
22 // Alice: 2 weeks ago - Add validation
23 if (!order.items || order.items.length === 0) {
24 throw new Error('Order must have items');
25 }
26=======
27 // Bob: 1 week ago - Add user check
28 if (!order.userId) {
29 throw new Error('Order must have a user');
30 }
31>>>>>>> feature/user-validation
32}
33
34// ✅ Resolution: Keep both validations
35function processOrder(order) {
36 if (!order.userId) {
37 throw new Error('Order must have a user');
38 }
39 if (!order.items || order.items.length === 0) {
40 throw new Error('Order must have items');
41 }
42 // Process order...
43}Modern IDEs provide visual interfaces for advanced Git operations like cherry-picking, rebasing, and interactive staging.
Git Stash - Save Work in Progress:
1// Scenario: Working on feature but need to switch branches
2
3// Current work (uncommitted):
4function newFeature() {
5 const data = fetchData();
6 const processed = processData(data); // Not finished yet
7 // TODO: Add more logic
8}
9
10// Emergency: Fix bug on main branch
11// Problem: Can't switch with uncommitted changes
12
13// Solution: Stash changes
14// 1. Command Palette → "Git: Stash"
15// 2. Enter description: "WIP: New feature data processing"
16// 3. Changes saved temporarily
17// 4. Working directory clean → Switch to main
18// 5. Fix bug, commit, push
19// 6. Switch back to feature branch
20// 7. Command Palette → "Git: Pop Stash"
21// 8. Continue working where you left off ✅
22
23// Stash operations:
24// - Stash → Save changes
25// - Stash (Include Untracked) → Save untracked files too
26// - Pop Stash → Apply and remove stash
27// - Apply Stash → Apply but keep stash
28// - Drop Stash → Delete stash
29// - View Stashes → See all stashed changes
30
31// Multiple stashes:
32// Stash 1: "WIP: Feature A"
33// Stash 2: "WIP: Feature B"
34// Stash 3: "Experimental changes"
35// → Apply specific stash when neededCherry-Pick - Apply Specific Commits:
1// Scenario: Want one commit from another branch
2
3// feature branch has:
4// Commit A: Bug fix (needed on main)
5// Commit B: Feature code (not ready)
6// Commit C: More feature code (not ready)
7
8// Want: Only commit A on main
9
10// Method 1: GitLens
11// 1. Open GitLens commit graph
12// 2. Find commit A
13// 3. Right-click → "Cherry Pick Commit"
14// 4. Commit A applied to current branch ✅
15
16// Method 2: Command Palette
17// "Git: Cherry Pick"
18// Enter commit hash
19
20// Example:
21// On main branch:
22function buggyFunction() {
23 return data.value; // Bug: might be undefined
24}
25
26// Cherry-pick commit A from feature branch:
27function buggyFunction() {
28 return data?.value ?? 'default'; // ✅ Fixed
29}
30
31// Commits B and C stay on feature branchInteractive Rebase - Rewrite History:
1// Clean up commit history before merging
2
3// Current feature branch commits:
4// 1. feat: Add user service
5// 2. fix typo
6// 3. fix: Handle edge case
7// 4. WIP
8// 5. feat: Add validation
9// 6. fix previous commit
10
11// 😱 Messy history with typos and WIP commits
12
13// Interactive rebase to clean up:
14// 1. Command Palette → "Git: Rebase"
15// 2. Select base commit (e.g., main)
16
17// Rebase editor shows:
18pick 1a2b3c4 feat: Add user service
19pick 2b3c4d5 fix typo
20pick 3c4d5e6 fix: Handle edge case
21pick 4d5e6f7 WIP
22pick 5e6f7g8 feat: Add validation
23pick 6f7g8h9 fix previous commit
24
25// Rebase operations:
26// pick → Keep commit as-is
27// reword → Change commit message
28// edit → Pause to modify commit
29// squash → Combine with previous commit
30// fixup → Combine but discard message
31// drop → Remove commit
32
33// Clean rebase plan:
34pick 1a2b3c4 feat: Add user service
35fixup 2b3c4d5 fix typo (merge into above)
36pick 3c4d5e6 fix: Handle edge case
37drop 4d5e6f7 WIP (remove)
38pick 5e6f7g8 feat: Add validation
39squash 6f7g8h9 fix previous (merge into above)
40
41// Result: Clean, professional commit history ✅
42// 1. feat: Add user service
43// 2. fix: Handle edge case
44// 3. feat: Add validation
45
46// ⚠️ Warning: Never rebase commits already pushed to shared branches!Amend Last Commit:
1// Made a commit but forgot something
2
3// Last commit:
4// "feat: Add login form"
5// - Added form component
6// - Added validation
7// - ❌ Forgot to add styles!
8
9// Add the forgotten file:
10// 1. Make the change (add styles)
11// 2. Stage the file
12// 3. Command Palette → "Git: Commit Staged (Amend)"
13// 4. Optionally update commit message
14// 5. Commit updates with new changes ✅
15
16// Result: Last commit now includes styles
17// No extra "fix: Add forgotten styles" commit
18
19// Before amend:
20git log
21// feat: Add login form
22// src/components/LoginForm.tsx
23// src/validators/login.ts
24
25// After amend:
26git log
27// feat: Add login form
28// src/components/LoginForm.tsx
29// src/validators/login.ts
30// src/styles/login.css ✅ Added
31
32// ⚠️ Only amend commits not yet pushed!Git Blame and File History:
1// Find out who changed a line and why
2
3// Method 1: Inline blame (GitLens)
4function calculateDiscount(price) {
5 // Alice, 2 months ago: Initial implementation
6 const discount = price * 0.1;
7
8 // Bob, 1 month ago: Fix: Use correct rate
9 const tax = price * 0.08;
10
11 // Carol, 1 week ago: Add validation
12 if (price < 0) {
13 throw new Error('Invalid price');
14 }
15
16 return price - discount + tax;
17}
18
19// Each line shows:
20// - Author name
21// - Commit date
22// - Commit message
23// → Click to see full commit
24
25// Method 2: File annotations
26// Command Palette → "GitLens: Toggle File Blame"
27// Shows blame info for entire file
28
29// Method 3: Line history
30// Right-click line → "Show Line History"
31// See all commits that modified this line
32
33// Example use case:
34// Bug on line 42 → Check blame
35// See: Bob changed it 1 week ago in commit abc123
36// Open commit → See full context
37// Understand why change was made
38// Fix bug with proper understanding ✅Git Tags and Releases:
1// Mark important commits (releases, milestones)
2
3// Create tag:
4// 1. Command Palette → "Git: Create Tag"
5// 2. Enter tag name: v1.0.0
6// 3. Enter message: "First production release"
7// 4. Tag created at current commit ✅
8
9// View tags:
10// GitLens sidebar → Tags section
11// See all tags and their commits
12
13// Checkout tag:
14// Switch to specific release version
15// Right-click tag → "Checkout Tag"
16
17// Delete tag:
18// Right-click tag → "Delete Tag"
19
20// Push tags:
21// ... menu → "Push Tags"
22// Tags uploaded to remote repository
23
24// Tag naming conventions:
25// v1.0.0 - Semantic versioning
26// v2.1.3 - Major.Minor.Patch
27// release-2024-01 - Date-based
28// beta-1.0 - Pre-release versionsGit Worktrees - Multiple Checkouts:
1# Work on multiple branches simultaneously
2
3# Scenario: Need to compare two branches
4# Or: Work on feature while reviewing PR
5
6# Traditional approach:
7# - Stash changes
8# - Switch branches
9# - Review code
10# - Switch back
11# - Pop stash
12# 😰 Tedious!
13
14# Worktree approach:
15# - Keep main branch in main directory
16# - Create worktree for feature branch
17# - Work on both simultaneously ✅
18
19# Create worktree (Terminal in VS Code):
20git worktree add ../feature-branch feature/new-ui
21
22# Result:
23# Original: /project/ (main branch)
24# Worktree: /feature-branch/ (feature/new-ui branch)
25
26# Open both in VS Code:
27# - Window 1: /project/
28# - Window 2: /feature-branch/
29# - Edit both simultaneously
30# - Compare code side-by-side
31
32# Remove worktree when done:
33git worktree remove ../feature-branchReflog - Recover Lost Commits:
1// Accidentally deleted a commit? Reflog can save you!
2
3// Scenario: Did a hard reset and lost commits
4// git reset --hard HEAD~3 // Oops! Lost 3 commits
5
6// View reflog:
7// Command Palette → "Git: View Reflog"
8
9// Shows all HEAD movements:
10// abc1234 HEAD@{0}: reset: moving to HEAD~3
11// def5678 HEAD@{1}: commit: Add user profile ← Lost commit!
12// ghi9012 HEAD@{2}: commit: Fix bug
13// jkl3456 HEAD@{3}: commit: Update docs
14
15// Recover lost commit:
16// Find the lost commit hash (def5678)
17// git checkout def5678
18// Or create branch: git branch recovered def5678
19
20// ✅ Lost commit recovered!Enhance your Git workflow with powerful extensions that provide visual interfaces and advanced features.
GitLens - Supercharge Git in VS Code:
1// Installation: VS Code Extensions → Search "GitLens"
2
3// Key Features:
4
5// 1. INLINE BLAME - See who changed each line
6function calculatePrice(items) { // Alice, 2 weeks ago: Add pricing
7 const subtotal = items.reduce( // Bob, 1 week ago: Use reduce
8 (sum, item) => sum + item.price,
9 0
10 );
11 return subtotal;
12}
13// Hover any line → See full commit details
14
15// 2. FILE ANNOTATIONS
16// Shows blame info in gutter
17// Color-coded by author
18// Click to see commit message
19
20// 3. COMMIT GRAPH
21// Visual branch and commit history
22// See relationships between branches
23// Identify merge points
24// Navigate commits visually
25
26// 4. FILE HISTORY
27// Timeline of all changes to a file
28// See evolution over time
29// Compare any two versions
30// Restore old versions
31
32// 5. COMPARE BRANCHES
33// Side-by-side branch comparison
34// See all differences
35// Files added/modified/deleted
36// Line-by-line changes
37
38// 6. HOVERS AND INSIGHTS
39// Hover over:
40// - Commit hash → See commit details
41// - Branch name → See branch info
42// - Status bar items → Quick actions
43
44// GitLens Settings:
45{
46 "gitlens.currentLine.enabled": true,
47 "gitlens.hovers.currentLine.over": "line",
48 "gitlens.codeLens.enabled": true,
49 "gitlens.blame.format": "${author}, ${date}",
50 "gitlens.defaultDateFormat": "MMMM Do, YYYY h:mma"
51}Git Graph - Visual Branch Management:
1// Installation: VS Code Extensions → Search "Git Graph"
2
3// Features:
4
5// 1. VISUAL COMMIT HISTORY
6/*
7 ●─────●─────● main
8 ╲ ╱
9 ●─────● feature/auth
10*/
11
12// Click "Git Graph" button in Source Control
13// See full commit history as a graph
14// Branches visualized as colored lines
15// Commits as dots on timeline
16
17// 2. BRANCH OPERATIONS
18// Right-click any commit:
19// - Checkout
20// - Create branch
21// - Cherry-pick
22// - Revert
23// - Reset to this commit
24// - Copy commit hash
25
26// 3. FILE CHANGES VIEW
27// Click any commit → See all changed files
28// Click file → See diff
29// Navigate through history visually
30
31// 4. COMPARE COMMITS
32// Select two commits
33// See all differences
34// Great for code review
35
36// Example workflow:
37// 1. Open Git Graph
38// 2. See feature branch diverged from main
39// 3. Right-click feature branch tip
40// 4. Select "Merge into current branch"
41// 5. Resolve conflicts if any
42// 6. See merge commit in graph ✅Git History - File and Line History:
1// Installation: VS Code Extensions → Search "Git History"
2
3// Features:
4
5// 1. FILE HISTORY
6// Right-click file → "Git: View File History"
7// See all commits that modified this file
8// Timeline view with commit messages
9// Click to see changes in each commit
10
11// 2. LINE HISTORY
12// Select lines in editor
13// Right-click → "Git: View Line History"
14// See all commits that modified these lines
15// Track evolution of specific code
16
17// Example:
18function authenticateUser(username, password) {
19 // Select these lines
20 // Right-click → View Line History
21 // See: 5 commits modified this function
22 // - Initial implementation
23 // - Add password hashing
24 // - Add rate limiting
25 // - Fix security issue
26 // - Add logging
27}
28
29// 3. COMPARE BRANCHES
30// Command Palette → "Git: Compare..."
31// Select two branches
32// See all file differences
33
34// 4. COMMIT SEARCH
35// Search commits by:
36// - Message
37// - Author
38// - Date range
39// - File pathGitHub Pull Requests - PR in VS Code:
1// Installation: "GitHub Pull Requests and Issues"
2
3// Features:
4
5// 1. VIEW PRS IN EDITOR
6// Sidebar → GitHub icon
7// See all PRs in repository
8// Filter by: Open, Closed, Mine, Assigned to me
9
10// 2. CREATE PR
11// Push branch → Click "Create Pull Request"
12// Fill form in VS Code:
13// - Title
14// - Description
15// - Reviewers
16// - Labels
17// Submit without leaving editor ✅
18
19// 3. CODE REVIEW
20// Open PR → See changed files
21// Add comments inline
22// Approve or request changes
23// All in VS Code
24
25// 4. CHECKOUT PR
26// Click PR → "Checkout"
27// Test PR locally
28// Add comments
29// Approve from editor
30
31// Example PR review workflow:
32// 1. Teammate creates PR
33// 2. Notification appears in VS Code
34// 3. Click PR → See changes
35// 4. Review code file by file
36// 5. Add inline comments:
37// "Consider using const instead of let here"
38// 6. Approve or request changes
39// 7. Merge when ready
40// All without browser! ✅GitKraken Glo Boards - Project Management:
1// Integrate tasks with Git commits
2
3// Features:
4// - Kanban boards in VS Code
5// - Link commits to tasks
6// - Track progress visually
7// - Sync with GitHub Issues
8
9// Example workflow:
10// 1. Create task: "Add user authentication"
11// 2. Move to "In Progress"
12// 3. Work on code
13// 4. Commit with task reference:
14// "feat: Add JWT auth (Closes #123)"
15// 5. Task automatically moves to "Done" ✅Git Extension Settings Best Practices:
1// .vscode/settings.json
2
3{
4 // GitLens settings
5 "gitlens.currentLine.enabled": true,
6 "gitlens.hovers.currentLine.over": "line",
7 "gitlens.codeLens.enabled": true,
8 "gitlens.codeLens.authors.enabled": false,
9 "gitlens.codeLens.recentChange.enabled": false,
10
11 // Git settings
12 "git.enableSmartCommit": true,
13 "git.confirmSync": false,
14 "git.autofetch": true,
15 "git.pruneOnFetch": true,
16
17 // Git Graph settings
18 "git-graph.showStatusBarItem": true,
19 "git-graph.dateFormat": "ISO Date & Time",
20
21 // Source control
22 "scm.defaultViewMode": "tree",
23 "scm.diffDecorations": "all"
24}Productivity Tips with Git Extensions:
1// Tip 1: Use GitLens blame before changing code
2// - Understand context
3// - See why code was written
4// - Avoid breaking existing logic
5
6// Tip 2: Git Graph for complex merges
7// - Visualize branch structure
8// - Identify merge base
9// - Plan merge strategy
10
11// Tip 3: File history for debugging
12// - Bug appeared recently?
13// - Check file history
14// - Find the commit that introduced bug
15// - Understand what changed
16
17// Tip 4: Branch comparison before merge
18// - Compare feature with main
19// - Review all changes
20// - Catch issues early
21
22// Tip 5: Stash frequently
23// - Experimental changes?
24// - Stash instead of committing
25// - Try different approaches
26// - Apply best solution
27
28// Tip 6: Use commit search
29// - Find that important commit
30// - Search by message, author, or date
31// - No need to scroll through history
32
33// Tip 7: Inline blame during code review
34// - Understand who wrote what
35// - Ask questions to right person
36// - Better context for review commentsEstablish efficient Git workflows using your IDE to maintain code quality and team productivity.
Feature Branch Workflow:
1// Standard workflow for new features
2
3// 1. START: Create feature branch from main
4// Status bar: Click "main" → Create branch → "feature/user-profile"
5
6// 2. DEVELOP: Work on feature
7// Make changes, commit regularly
8function createUserProfile(data) {
9 return {
10 ...data,
11 createdAt: new Date()
12 };
13}
14
15// Commit: "feat: Add user profile creation"
16
17// 3. SYNC: Keep up-to-date with main
18// Periodically: Pull main and merge into feature
19// ... menu → Pull → Select "main"
20// ... menu → Merge Branch → Select "main"
21// Resolve conflicts if any
22
23// 4. REVIEW: Create pull request
24// Push feature branch
25// GitHub extension → Create PR
26// Request reviews
27
28// 5. MERGE: Complete the feature
29// After approval → Merge PR
30// Delete feature branch
31// Pull main to get merged changes
32
33// Result: Clean, reviewable, traceable changes ✅Commit Best Practices:
1// ✅ Good commit practices:
2
3// 1. ATOMIC COMMITS - One logical change per commit
4// Commit 1: "feat: Add user model"
5class User {
6 constructor(data) { ... }
7}
8
9// Commit 2: "feat: Add user service"
10class UserService {
11 create(data) { ... }
12}
13
14// ❌ Bad: One huge commit
15// "Add user feature" - 50 files changed
16
17// 2. DESCRIPTIVE MESSAGES
18// ✅ "fix: Resolve memory leak in cache invalidation"
19// ❌ "fix stuff"
20
21// 3. CONVENTIONAL COMMITS
22// feat: New feature
23// fix: Bug fix
24// docs: Documentation
25// style: Formatting
26// refactor: Code restructuring
27// test: Adding tests
28// chore: Maintenance
29
30// Examples:
31// "feat: Add email verification"
32// "fix: Handle null user in authentication"
33// "docs: Update API documentation"
34// "refactor: Extract validation to separate module"
35
36// 4. USE COMMIT MESSAGE BODY
37// First line: Summary (50 chars)
38// Blank line
39// Body: Detailed explanation
40
41// Example:
42/*
43feat: Add rate limiting to API
44
45Implements rate limiting using Redis to prevent abuse.
46Limits: 100 requests per hour per IP address.
47Returns 429 status when limit exceeded.
48
49Closes #123
50*/
51
52// 5. REFERENCE ISSUES
53// Link commits to issues/tickets
54// "fix: Handle edge case in validation (Fixes #456)"
55// "feat: Add dark mode (Implements #789)"Code Review Workflow:
1// Reviewing PRs in VS Code
2
3// 1. OPEN PR
4// GitHub extension → Pull Requests
5// Click PR to review
6
7// 2. CHECKOUT PR BRANCH
8// Click "Checkout" button
9// Code appears in editor
10// Test locally
11
12// 3. REVIEW FILES
13// See all changed files
14// Click each file to review
15
16// 4. ADD COMMENTS
17// Inline comments on specific lines:
18// Right-click line → "Add Comment"
19
20// Example review comments:
21// ✅ Good comments:
22// "Consider using async/await for better readability"
23// "This could cause a memory leak. Store in WeakMap instead?"
24// "Great use of TypeScript generics here!"
25
26// ❌ Bad comments:
27// "This is wrong"
28// "Fix this"
29
30// 5. SUGGEST CHANGES
31// Propose code changes directly:
32function getUser(id) {
33 // Your suggestion:
34 if (!id) {
35 throw new Error('User ID required');
36 }
37 return users.find(id);
38}
39
40// 6. APPROVE OR REQUEST CHANGES
41// After review → Approve or Request Changes
42// Merge when all checks passHandling Large Repositories:
1// Performance tips for large repos
2
3// 1. SPARSE CHECKOUT
4// Only checkout files you need
5// Faster clone and operations
6
7// Terminal in VS Code:
8git sparse-checkout init --cone
9git sparse-checkout set src/frontend
10
11// Now only src/frontend is checked out
12// Other directories ignored
13
14// 2. SHALLOW CLONE
15// Clone without full history
16git clone --depth 1 https://github.com/user/repo.git
17
18// Get only latest commit
19// Much faster for large repos
20
21// 3. .gitignore OPTIMIZATION
22// Ignore large directories:
23node_modules/
24dist/
25.next/
26coverage/
27*.log
28
29// 4. FILE SEARCH EXCLUSIONS
30// .vscode/settings.json
31{
32 "search.exclude": {
33 "**/node_modules": true,
34 "**/dist": true,
35 "**/.git": true
36 },
37 "files.watcherExclude": {
38 "**/node_modules/**": true
39 }
40}Git Hooks Integration:
1// Automate checks with Git hooks
2
3// Pre-commit hook - Run linters
4// .husky/pre-commit
5#!/bin/sh
6npm run lint
7npm run type-check
8
9// VS Code shows:
10// Committing...
11// → Running pre-commit hook
12// → ESLint check... ✅
13// → TypeScript check... ✅
14// → Commit successful
15
16// If checks fail:
17// ❌ ESLint errors found
18// Commit blocked
19// Fix errors → Try again
20
21// Pre-push hook - Run tests
22// .husky/pre-push
23#!/bin/sh
24npm test
25
26// Pushing...
27// → Running pre-push hook
28// → Tests running...
29// → All tests passed ✅
30// → Push successful
31
32// Hooks ensure quality before sharing code ✅Collaboration Best Practices:
1// Working effectively with team
2
3// 1. PULL BEFORE PUSH
4// Always pull latest changes first
5// Reduces conflicts
6// ... menu → Pull → Push
7
8// 2. SYNC FREQUENTLY
9// Sync button in status bar
10// Click to pull and push
11// Stay up-to-date with team
12
13// 3. COMMUNICATE IN COMMITS
14// Write clear messages
15// Reference issues
16// Explain WHY, not just WHAT
17
18// Example:
19// ✅ "refactor: Extract auth logic to middleware
20//
21// Reduces duplication across route handlers
22// Makes testing easier
23// Implements security review feedback #234"
24
25// ❌ "update code"
26
27// 4. RESOLVE CONFLICTS PROMPTLY
28// Don't let conflicts pile up
29// Resolve as soon as detected
30// Ask teammate if unclear
31
32// 5. CODE REVIEW ETIQUETTE
33// - Review within 24 hours
34// - Be constructive and kind
35// - Explain your suggestions
36// - Approve quickly if looks good
37// - Don't nitpick formatting (use Prettier!)
38
39// 6. BRANCH NAMING CONSISTENCY
40// Team convention:
41// feature/description
42// fix/issue-number
43// refactor/component-name
44
45// Everyone follows same pattern
46// Easy to understand branch purposeTroubleshooting Common Issues:
1// Issue 1: Merge conflict too complex
2// Solution: Abort and discuss with team
3// ... menu → Abort Merge
4// Coordinate with teammate
5
6// Issue 2: Accidentally committed to wrong branch
7// Solution: Cherry-pick to correct branch
8// 1. Switch to correct branch
9// 2. Cherry-pick the commit
10// 3. Delete commit from wrong branch (reset)
11
12// Issue 3: Need to undo last commit
13// Solution: Reset soft (keeps changes)
14// Command Palette → "Git: Undo Last Commit"
15// Changes go back to staged
16
17// Issue 4: Pushed wrong code
18// Solution: Revert commit (safe for shared branches)
19// Right-click commit → "Revert Commit"
20// Creates new commit that undoes changes
21
22// Issue 5: Lost work after bad merge
23// Solution: Use reflog
24// Command Palette → "Git: View Reflog"
25// Find commit before merge
26// Create branch from that commit
27
28// Issue 6: Can't push (diverged branches)
29// Solution: Pull with rebase
30// ... menu → Pull (Rebase)
31// Replays your commits on top of remoteYour progress is saved in this browser, on this device only.