This document outlines production-grade standards and workflows for Git usage throughout the application lifecycle.
Table of Contents
- Initial Setup
- Repository Creation
- Branching Strategy
- Daily Development Workflow
- Pull Request Process
- Release Management
- GitHub Integration
- Advanced Git Techniques
Initial Setup
Git Installation & Configuration
# Install Git (Windows using Chocolatey)
choco install git
# Configure your identity
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Configure default branch name
git config --global init.defaultBranch main
# Configure line ending preferences
git config --global core.autocrlf true # Windows
# git config --global core.autocrlf input # Mac/Linux
# Setup credential helper for HTTPS
git config --global credential.helper manager-core # WindowsBashSSH Key Configuration (Recommended)
# Generate SSH key
ssh-keygen -t ed25519 -C "your.email@example.com"
# Start ssh-agent
eval "$(ssh-agent -s)" # Mac/Linux
# For Windows, use Git Bash or:
# start-ssh-agent.cmd
# Add your SSH key to the agent
ssh-add ~/.ssh/id_ed25519
# Copy the public key to clipboard for GitHub
clip < ~/.ssh/id_ed25519.pub # Windows
# pbcopy < ~/.ssh/id_ed25519.pub # MacBashAdd the key to GitHub: Settings → SSH and GPG keys → New SSH key
Repository Creation
New Project Initialization
# Create a new directory
mkdir project-name
cd project-name
# Initialize Git repository
git init
# Create essential files
touch README.md .gitignore LICENSE
# Create initial commit
git add .
git commit -m "Initial commit"BashConnect to GitHub
# Create repository on GitHub first, then:
# Option 1: Using HTTPS
git remote add origin https://github.com/username/repository.git
# Option 2: Using SSH (preferred)
git remote add origin git@github.com:username/repository.git
# Push to GitHub
git push -u origin mainBashTemplate .gitignore
Always include a .gitignore file appropriate for your project. Use gitignore.io or GitHub’s templates.
Branching Strategy
GitFlow Strategy
main : Production-ready code
├── develop : Integration branch for features
│ ├── feature/name : New features
│ ├── bugfix/name : Bug fixes
├── release/v1.0.0 : Release preparation
├── hotfix/name : Production hotfixesBashCommands for Branch Management
# Create and switch to a new feature branch
git checkout -b feature/user-authentication develop
# Push feature branch to remote
git push -u origin feature/user-authentication
# Create release branch
git checkout -b release/v1.0.0 develop
# Merge release into main
git checkout main
git merge --no-ff release/v1.0.0
git tag -a v1.0.0 -m "Version 1.0.0"
git push --follow-tagsBashDaily Development Workflow
Standard Workflow
# Get latest changes
git checkout develop
git pull
# Create feature branch
git checkout -b feature/new-feature
# Work and make commits
# ... make changes to code ...
git add .
git commit -m "feat: add new feature"
# Regularly sync with develop
git checkout develop
git pull
git checkout feature/new-feature
git rebase develop
# Push feature to remote
git push -u origin feature/new-featureBashCommit Message Standards
Follow Conventional Commits format:
<type>(<scope>): <description>
[optional body]
[optional footer(s)]BashTypes: feat, fix, docs, style, refactor, test, chore, perf
Pull Request Process
- Create PR in GitHub targeting
developbranch - Fill PR template with:
- Description of changes
- Issue references
- Testing performed
- Screenshots (if UI changes)
- Request reviews
- Address feedback
- Merge after approval (use squash merging for feature branches)
Release Management
# Create release branch
git checkout -b release/v1.2.0 develop
# Bump version numbers in appropriate files
# ... update version.json, package.json, etc ...
git commit -a -m "chore: bump version to 1.2.0"
# Finalize release
git checkout main
git merge --no-ff release/v1.2.0 -m "chore: release v1.2.0"
git tag -a v1.2.0 -m "Version 1.2.0"
# Update develop
git checkout develop
git merge --no-ff release/v1.2.0
git push origin develop
# Push main and tags
git checkout main
git push origin main --tags
# Delete release branch
git branch -d release/v1.2.0
git push origin --delete release/v1.2.0BashGitHub Integration
GitHub Actions CI/CD
Create .github/workflows/ci.yml:
name: CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup environment
uses: actions/setup-node@v3
with:
node-version: '18.x'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run buildYAMLBranch Protection Rules
Configure in GitHub repository settings:
- Require pull request reviews
- Require status checks to pass
- Require linear history (rebase merging)
- No direct pushes to main/develop
Advanced Git Techniques
Interactive Rebase
# Cleanup commits before PR
git rebase -i HEAD~5 # Rebase last 5 commitsBashCherry-picking
# Apply specific commit to current branch
git cherry-pick abc123fBashStashing Changes
# Stash uncommitted changes
git stash save "WIP: feature implementation"
# List stashes
git stash list
# Apply stashed changes
git stash apply stash@{0}BashGit Hooks
Use pre-commit hooks for linting and testing. Install pre-commit and configure .pre-commit-config.yaml.
Note: Adapt this workflow to your team’s specific needs. The most important aspect is consistency across the team and adherence to the agreed-upon standards.
Git Command Cheatsheet and Advanced Practices
Comprehensive Git Command Cheatsheet
Repository Operations
# Clone with specific options
git clone --depth=1 <repository-url> # Shallow clone (minimal history)
git clone --branch=<branch> <repo-url> # Clone specific branch
git clone --recurse-submodules <repo-url> # Clone with submodules
# Remote management
git remote -v # List remote repositories
git remote set-url origin <new-url> # Change remote URL
git remote prune origin # Remove deleted remote branches references
# Submodules
git submodule add <repo-url> <path> # Add a submodule
git submodule update --init --recursive # Initialize and update all submodulesBashInspecting Changes
# Status and diff commands
git status -s # Short status output
git diff --staged # View staged changes
git diff --word-diff # Show word-level differences
git diff <commit>..<commit> # Compare two commits
git diff --name-only # Show only changed filenames
# Log variations
git log --graph --oneline --decorate # Graphical representation
git log -p <file> # File history with patches
git log --author="username" # Filter by author
git log --since="2 weeks ago" # Filter by date
git log -S"<string>" # Search for string in history
git log --pretty=format:"%h - %an, %ar : %s" # Custom format
# History exploration
git blame <file> # Show who changed what and when
git reflog # Show all reference changes
git shortlog -sn # Summary of commits by authorBashWorkflow Efficiency
# Staging and committing
git add -p # Interactively stage parts of files
git commit --amend # Modify the last commit
git commit --fixup=<commit> # Mark as fix for a previous commit
# Stashing with options
git stash push -m "message" # Stash with description
git stash --include-untracked # Also stash untracked files
git stash --patch # Interactively stash changes
git stash branch <branch-name> # Create branch from stash
git stash drop stash@{n} # Remove specific stash
git stash clear # Remove all stashes
# Workspace management
git clean -df # Remove untracked files and directories
git checkout -- . # Discard all unstaged changes
git restore --staged <file> # Unstage file (Git 2.23+)
git restore <file> # Discard changes (Git 2.23+)BashBranch Management
# Branch operations
git branch -vv # List branches with tracking info
git branch -m <old-name> <new-name> # Rename branch
git branch --merged # List merged branches
git branch --no-merged # List unmerged branches
# Advanced merge and rebase
git merge --squash <branch> # Squash merge
git merge --abort # Abort a merge in progress
git rebase --onto <new-base> <old-base> # Change branch base
git rebase -i <base-commit> # Interactive rebase
git rebase --autosquash <base-commit> # Auto-arrange fixup commits
# Branch cleanup
git fetch --prune # Prune local references to deleted remote branches
git branch | grep -v "main\|develop" | xargs git branch -D # Delete all branches except main and developBashTags and Releases
# Tag management
git tag -a v1.2.0 -m "Version 1.2.0" # Create annotated tag
git tag -l "v1.*" # List tags matching pattern
git push --tags # Push all tags
git tag -d <tag-name> # Delete local tag
git push --delete origin <tag-name> # Delete remote tag
# Release management
git archive --format=zip HEAD -o latest.zip # Create archive of current HEAD
git describe --tags # Get nearest tag with commit infoBashGit Aliases for Productivity
Add these to your .gitconfig file:
[alias]
# Basic shortcuts
st = status
co = checkout
br = branch
ci = commit
# Enhanced logging
lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
recent = for-each-ref --sort=-committerdate --count=10 --format='%(refname:short)' refs/heads/
# Workflow helpers
undo = reset HEAD~1 --mixed # Undo last commit but keep changes
amend = commit --amend --no-edit # Amend commit without changing message
unstage = restore --staged . # Unstage all changes
# Code review assistance
changes = diff --name-status
differ = diff --word-diff=color
last = log -1 HEAD --stat
# Branch management
delete-merged = !git branch --merged | grep -v '\\*\\|main\\|master\\|develop' | xargs -n 1 git branch -dBashGit Troubleshooting Guide
Resolving Common Issues
# Fix detached HEAD state
git checkout <branch-name>
# Recover lost commits (after a reset)
git reflog show
git checkout -b recovery-branch <commit-hash>
# Fix conflicts during merge/rebase
git mergetool # Use visual merge tool
git rebase --abort # Cancel a problematic rebase
git merge --abort # Cancel a problematic merge
# Fix incorrect author information
git commit --amend --author="Name <email@example.com>"
# Fix committed but not pushed secrets
git filter-branch --force --tree-filter 'rm -f path/to/file' HEAD --all
# Better solution: Use BFG Repo-Cleaner tool
# Recover deleted stashes
git fsck --unreachable | grep commit | cut -d ' ' -f3 | xargs git showBashGit for Large Repositories
# Partial clone
git clone --filter=blob:none <repository-url> # Clone without file contents
# Sparse checkout
git clone --no-checkout <repository-url>
cd repo
git sparse-checkout set <directory1> <directory2>
git checkout
# Managing large files
# Install Git LFS first
git lfs install
git lfs track "*.psd" # Track large file types
git add .gitattributesBashGit Security Best Practices
Securing Your Repository
# Verify commits
git config --global user.signingkey <key-id>
git config --global commit.gpgsign true
# Sign commits
git commit -S -m "Signed commit message"
# Sign tags
git tag -s v1.0.0 -m "Signed tag"
# Verify signed tag
git verify-tag v1.0.0BashSecret Management
- Use
.gitignoreto prevent committing sensitive files - Consider using git-secrets, Talisman or pre-commit hooks to detect secrets
- Set up server-side hooks to reject commits with secrets
# Example pre-commit hook to detect secrets (install pre-commit first)
cat > .pre-commit-config.yaml << EOF
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.16.1
hooks:
- id: gitleaks
EOFBashGit for DevOps
CI/CD Integration
# Check if pipeline commands will succeed
git fetch origin main:refs/remotes/origin/main # Get latest main
git diff --name-status origin/main..HEAD # Files changed
git diff --stat origin/main..HEAD # Stats on changes
# Create deployment tag
git tag -a deploy-$(date +%Y%m%d-%H%M%S) -m "Deployment tag"
# Get last successful deployment
git describe --tags --abbrev=0BashAdvanced Git Hooks
Create .git/hooks/pre-push:
#!/bin/bash
# Example pre-push hook to prevent force-pushing to main
protected_branch='main'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
push_command=$(ps -ocommand= -p $PPID)
if [[ $push_command =~ --force ]] && [ $current_branch = $protected_branch ]; then
echo "Force-pushing to $protected_branch is not allowed."
exit 1
fi
exit 0BashMonorepo Management
# Detect changes in subdirectory since last tag
git diff --name-only $(git describe --tags --abbrev=0)..HEAD -- path/to/service/
# Create worktree for parallel work
git worktree add -b feature-x ../path-to-new-worktree
# List active worktrees
git worktree listBashResources:
Remember: These advanced techniques should be used with caution and understanding. Document your team’s accepted practices clearly to maintain consistency across projects.
Discover more from Altgr Blog
Subscribe to get the latest posts sent to your email.
