Practice and reinforce the concepts from Lesson 2
By the end of this workshop, you will:
Create a production-ready project structure following industry standards:
# Create project directory with meaningful name
mkdir tech-company-api && cd tech-company-api
# Initialize Git repository with default branch name
git init -b main
# Configure repository-specific settings
git config --local core.autocrlf input
git config --local core.ignorecase false
git config --local pull.rebase true
# Create professional project structure
mkdir -p src/{controllers,models,utils} tests docs config
touch README.md LICENSE CONTRIBUTING.md .gitignore
touch src/index.js config/database.js tests/unit.test.js
# Verify repository initialization
git status
ls -la .git/
Scenario: You're starting a new microservice at a tech company
Solution: Proper repository initialization ensures consistent team workflow
Impact: Reduces merge conflicts and maintains code quality standards
Create a comprehensive .gitignore
file:
# Environment and dependencies
node_modules/
.env
.env.*
!.env.example
# Build outputs
dist/
build/
*.bundle.js
*.bundle.js.map
# IDE configurations
.vscode/
.idea/
*.swp
*.swo
.DS_Store
# Logs and databases
*.log
npm-debug.log*
*.sqlite
*.db
# Testing
coverage/
.nyc_output/
*.lcov
# Security
*.pem
*.key
secrets/
# Verify gitignore effectiveness
echo "SECRET_KEY=abc123" > .env
mkdir node_modules && touch node_modules/test.js
git status # Should not show ignored files
Initial Project Setup:
// src/index.js
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const { errorHandler } = require('./utils/errorHandler');
const app = express();
const PORT = process.env.PORT || 3000;
// Security middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).json({ status: 'healthy', timestamp: new Date() });
});
// Error handling
app.use(errorHandler);
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
# Stage and examine changes before committing
git add src/index.js
git diff --staged
git status -s
# Commit with conventional commit message
git commit -m "feat: initialize Express server with security middleware
- Add helmet for security headers
- Configure CORS for cross-origin requests
- Implement health check endpoint
- Add global error handler"
# Add error handler utility
// src/utils/errorHandler.js
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
const errorHandler = (err, req, res, next) => {
const { statusCode = 500, message } = err;
res.status(statusCode).json({
status: 'error',
statusCode,
message: statusCode === 500 ? 'Internal server error' : message,
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
});
};
module.exports = { AppError, errorHandler };
# Stage and commit utility
git add src/utils/errorHandler.js
git commit -m "feat: add custom error handling utilities
- Create AppError class for operational errors
- Implement Express error middleware
- Add stack trace in development mode"
Follow the Conventional Commits specification:
feat:
New featurefix:
Bug fixdocs:
Documentation changesstyle:
Code style changes (formatting, semicolons)refactor:
Code refactoringtest:
Adding or updating testschore:
Maintenance tasksperf:
Performance improvements# Custom log formats for different purposes
# Development review format
git log --pretty=format:"%h - %an, %ar : %s" -10
# Release notes format
git log --pretty=format:"* %s (%h)" --since="2 weeks ago"
# Detailed commit inspection
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
# Find commits affecting specific files
git log --follow -- src/index.js
# Search commit messages
git log --grep="security" -i
# Find commits by code changes
git log -S "errorHandler" --source --all
# Compare working directory with any commit
git diff HEAD~3
# Show word-level differences
git diff --word-diff
# Generate patch files
git diff > feature-changes.patch
# Show only file names that changed
git diff --name-only HEAD~5
# Show statistics of changes
git diff --stat HEAD~10
# Ignore whitespace changes
git diff -w
# Compare between branches (preview merge conflicts)
git diff main..feature-branch
Scenario: Code review before deployment
Solution: Use advanced git log and diff to analyze changes
Impact: Catch potential issues before they reach production
# Interactive staging for precise commits
git add -i
# Stage hunks of changes selectively
git add -p src/index.js
# Stage all tracked files with modifications
git add -u
# Stage everything except certain patterns
git add . ':!*.log' ':!node_modules'
# Dry run to see what would be added
git add -n .
# Stage files matching a pattern
git add '*.js'
# Soft reset - keep changes staged
git reset --soft HEAD~1
# Mixed reset - keep changes unstaged (default)
git reset HEAD~1
# Hard reset - discard all changes (DANGEROUS)
git reset --hard HEAD~1
# Reset specific file to previous state
git checkout HEAD~2 -- src/index.js
# Create backup branch before dangerous operations
git branch backup-before-reset
# Recover from accidental reset using reflog
git reflog
git reset --hard HEAD@{2}
Issue: Accidentally committed sensitive data
# Remove file from history (requires force push)
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch .env" \
--prune-empty --tag-name-filter cat -- --all
# Alternative: Use BFG Repo-Cleaner
java -jar bfg.jar --delete-files .env
Issue: Committed to wrong branch
# Move commit to correct branch
git log -1 # Note commit hash
git reset --hard HEAD~1
git checkout correct-branch
git cherry-pick [commit-hash]
Issue: Need to split a large commit
# Reset to before the commit
git reset HEAD~1
# Stage and commit in smaller chunks
git add -p
git commit -m "feat: add authentication module"
git add -p
git commit -m "feat: add user validation"
# Global configurations for productivity
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
# Professional aliases for common workflows
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
git config --global alias.contributors "shortlog --summary --numbered"
git config --global alias.undo 'reset --soft HEAD~1'
# Performance optimizations
git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256
# Security configurations
git config --global init.defaultBranch main
git config --global core.sshCommand "ssh -i ~/.ssh/company_rsa"
Create a pre-commit hook (.git/hooks/pre-commit
):
#!/bin/sh
# Run tests before commit
npm test
if [ $? -ne 0 ]; then
echo "Tests failed. Commit aborted."
exit 1
fi
# Check for console.log statements
if git diff --cached --name-only | grep -E '\.(js|ts)
chmod +x .git/hooks/pre-commit
## Part 6: Real-World Team Scenarios
### π Scenario 1: Hotfix Production Issue
**Context:** Critical bug in production needs immediate fix
git checkout main git pull origin main git checkout -b hotfix/payment-validation
git add src/controllers/paymentController.js git commit -m "fix: validate payment amount to prevent negative values
Fixes #1234"
npm test -- --grep "payment validation"
git push -u origin hotfix/payment-validation
### Scenario 2: Feature Branch Workflow
**Context:** Implementing new authentication system
git checkout -b feature/oauth-integration
git add src/auth/oauth.js git commit -m "wip: initial OAuth provider setup"
git add . git commit -m "feat: implement OAuth 2.0 authentication
Closes #456"
git rebase -i HEAD~3
### Scenario 3: Debugging with Git Bisect
**Context:** Finding when a bug was introduced
git bisect start git bisect bad HEAD git bisect good v1.2.0
git bisect good # if bug not present git bisect bad # if bug present
git bisect reset # return to original HEAD
git show [bad-commit-hash]
## π¨ Self-Assessment Checklist
Complete this checklist to validate your Git proficiency:
### Core Competencies
- [ ] Initialize and configure Git repositories with proper settings
- [ ] Create atomic, well-structured commits with conventional messages
- [ ] Navigate and analyze repository history effectively
- [ ] Manage staging area with precision (partial staging, hunks)
- [ ] Recover from common Git mistakes
- [ ] Configure Git aliases and productivity enhancements
- [ ] Implement Git hooks for quality control
- [ ] Handle merge conflicts professionally
- [ ] Use advanced Git commands (bisect, cherry-pick, rebase)
- [ ] Manage sensitive data and security considerations
### Practical Exercises
#### Exercise A: Repository Analysis
git clone https://github.com/nodejs/node.git cd node
git log --oneline -20 git shortlog -sn --no-merges git log --all --graph --decorate --oneline -20
git log --pretty=format: --name-only | sort | uniq -c | sort -rg | head -10
#### Exercise B: Advanced Workflow Simulation
1. Create a new repository
2. Implement a feature with 3-5 atomic commits
3. Create a bug and use git bisect to find it
4. Practice interactive rebase to clean up history
5. Set up Git hooks for code quality
### π Quick Reference: Essential Git Commands
<details>
<summary>Click to expand command reference</summary>
| Category | Command | Purpose |
|----------|---------|---------|
| **Setup** | `git init -b main` | Initialize with custom branch |
| **Staging** | `git add -p` | Stage hunks interactively |
| **Commits** | `git commit --amend` | Modify last commit |
| **History** | `git log --grep="pattern"` | Search commit messages |
| **Branches** | `git checkout -b feature` | Create and switch branch |
| **Stashing** | `git stash save "message"` | Save work in progress |
| **Recovery** | `git reflog` | View all reference updates |
| **Remote** | `git remote -v` | List remote repositories |
| **Tags** | `git tag -a v1.0.0 -m "msg"` | Create annotated tag |
| **Debug** | `git bisect` | Binary search for bugs |
</details>
## π‘ Pro Tips for Git Mastery
1. **Commit Message Template**
```bash
git config --global commit.template ~/.gitmessage
Global .gitignore
git config --global core.excludesfile ~/.gitignore_global
Automatic Garbage Collection
git config --global gc.auto 256
Better Diff Tool
git config --global diff.tool vimdiff
After completing this workshop:
Remember: Professional Git usage is about more than commands-it's about maintaining clean, understandable project history that helps your team collaborate effectively. | xargs grep -n 'console.log' then echo "Remove console.log statements before committing" exit 1 fi
npm run lint if [ $? -ne 0 ]; then echo "Linting failed. Please fix errors before committing." exit 1 fi
__CODE_BLOCK_16__
## Part 6: Real-World Team Scenarios
### π Scenario 1: Hotfix Production Issue
**Context:** Critical bug in production needs immediate fix
__CODE_BLOCK_17__
### Scenario 2: Feature Branch Workflow
**Context:** Implementing new authentication system
__CODE_BLOCK_18__
### Scenario 3: Debugging with Git Bisect
**Context:** Finding when a bug was introduced
__CODE_BLOCK_19__
## π¨ Self-Assessment Checklist
Complete this checklist to validate your Git proficiency:
### Core Competencies
- [ ] Initialize and configure Git repositories with proper settings
- [ ] Create atomic, well-structured commits with conventional messages
- [ ] Navigate and analyze repository history effectively
- [ ] Manage staging area with precision (partial staging, hunks)
- [ ] Recover from common Git mistakes
- [ ] Configure Git aliases and productivity enhancements
- [ ] Implement Git hooks for quality control
- [ ] Handle merge conflicts professionally
- [ ] Use advanced Git commands (bisect, cherry-pick, rebase)
- [ ] Manage sensitive data and security considerations
### Practical Exercises
#### Exercise A: Repository Analysis
__CODE_BLOCK_20__
#### Exercise B: Advanced Workflow Simulation
1. Create a new repository
2. Implement a feature with 3-5 atomic commits
3. Create a bug and use git bisect to find it
4. Practice interactive rebase to clean up history
5. Set up Git hooks for code quality
### π Quick Reference: Essential Git Commands
<details>
<summary>Click to expand command reference</summary>
| Category | Command | Purpose |
|----------|---------|---------|
| **Setup** | __INLINE_CODE_10__ | Initialize with custom branch |
| **Staging** | __INLINE_CODE_11__ | Stage hunks interactively |
| **Commits** | __INLINE_CODE_12__ | Modify last commit |
| **History** | __INLINE_CODE_13__ | Search commit messages |
| **Branches** | __INLINE_CODE_14__ | Create and switch branch |
| **Stashing** | __INLINE_CODE_15__ | Save work in progress |
| **Recovery** | __INLINE_CODE_16__ | View all reference updates |
| **Remote** | __INLINE_CODE_17__ | List remote repositories |
| **Tags** | __INLINE_CODE_18__ | Create annotated tag |
| **Debug** | __INLINE_CODE_19__ | Binary search for bugs |
</details>
## π‘ Pro Tips for Git Mastery
1. **Commit Message Template**
__CODE_BLOCK_21__
2. **Global .gitignore**
__CODE_BLOCK_22__
3. **Automatic Garbage Collection**
__CODE_BLOCK_23__
4. **Better Diff Tool**
__CODE_BLOCK_24__
## π Further Learning
- **Official Documentation:** [Git SCM Documentation](https://git-scm.com/doc)
- **Interactive Tutorial:** [Learn Git Branching](https://learngitbranching.js.org/)
- **Advanced Guide:** [Pro Git Book](https://git-scm.com/book/en/v2)
- **Best Practices:** [Conventional Commits](https://www.conventionalcommits.org/)
- **Workflow Patterns:** [Git Flow](https://nvie.com/posts/a-successful-git-branching-model/)
## Next Steps
After completing this workshop:
1. Set up Git for your development environment
2. Practice the feature branch workflow
3. Contribute to an open-source project
4. Implement Git hooks in your projects
5. Learn about Git submodules and subtrees
---
**Remember:** Professional Git usage is about more than commandsβit's about maintaining clean, understandable project history that helps your team collaborate effectively.