Skip to content
IRC-Coding IRC-Coding
Git Version Control Branches Merge Conflicts Workflows DevOps Collaboration Software Development

Git Versioning: Branches, Merge Conflicts & Workflows

Master Git versioning with branches, merge conflicts, and collaborative workflows. Practical examples for team development.

S

schutzgeist

2 min read

Git Versioning: Fundamentals, Branches, Merge Conflicts & Workflows

Git is the world’s leading distributed version control system for software development. It enables efficient collaboration, change tracking, and secure code management.

Git Fundamentals

What is Git?

Git is a distributed version control system (Distributed Version Control System - DVCS) that was developed to simplify collaboration on software projects.

Core Concepts

# Initialize Git Repository
git init

# Clone repository
git clone https://github.com/user/repository.git

# Show status
git status

# Add changes
git add datei.txt
git add .

# Commit changes
git commit -m "Description of the change"

# Push changes
git push origin main

# Pull changes
git pull origin main

Git Architecture

# Work areas in Git
# Working Directory → Staging Area → Local Repository → Remote Repository

# Working Directory
echo "New content" > datei.txt

# Staging Area (Index)
git add datei.txt

# Local Repository
git commit -m "Commit change"

# Remote Repository
git push origin main

Git Configuration

Initial Configuration

# Configure username and email
git config --global user.name "Max Mustermann"
git config --global user.email "max@example.com"

# Set default editor
git config --global core.editor "vim"

# Default branch name (main instead of master)
git config --global init.defaultBranch main

# Display configuration
git config --list

# Repository-specific configuration
git config user.email "work@example.com"

Git Aliases

# Create useful aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'

# Use aliases
git st        # git status
git co main   # git checkout main
git br        # git branch
git ci -m "Message"  # git commit -m "Message"

Branches in Git

Branch Fundamentals

Branches enable parallel development on different features without affecting the main code.

# Create new branch
git branch feature-login

# Switch to branch
git checkout feature-login

# Create and switch to branch (combined)
git checkout -b feature-login

# Show all branches
git branch
git branch -a  # including remote branches

# Delete branch
git branch -d feature-login  # only if merged
git branch -D feature-login  # force

# Delete remote branch
git push origin --delete feature-login

Branch Strategies

# Feature Branch Workflow
# 1. Create new feature branch from main
git checkout main
git pull origin main
git checkout -b feature-user-authentication

# 2. Work on feature
git add .
git commit -m "Implement user authentication"
git push origin feature-user-authentication

# 3. Create pull request and merge
# 4. Delete branch after merge
git checkout main
git pull origin main
git branch -d feature-user-authentication

Branch Management

# Compare branches
git diff main feature-branch
git log main..feature-branch

# Merge branch
git checkout main
git merge feature-branch

# Rebase branch
git checkout feature-branch
git rebase main

# Cherry-pick (apply specific commits)
git checkout main
git cherry-pick <commit-hash>

# Stash (save changes temporarily)
git stash
git stash list
git stash pop
git stash apply
git stash drop

Merge Conflicts

What are Merge Conflicts?

Merge conflicts occur when Git cannot automatically decide which version of a file should be used.

Typical Conflict Situations

# Example: Two developers change the same line

# Developer A (Branch feature-a)
echo "console.log('Hello from Feature A');" > app.js
git add app.js
git commit -m "Add feature A logging"

# Developer B (Branch main)
echo "console.log('Hello from Main');" > app.js
git add app.js
git commit -m "Add main logging"

# Attempt merge
git checkout main
git merge feature-a

# CONFLICT: Merge conflict in app.js

Resolving Conflicts

# 1. Show conflict
git status

# 2. Open file and edit
# Git marks conflicts with <<<<<<<, =======, >>>>>>>

# app.js after conflict:
# <<<<<<< HEAD
# console.log('Hello from Main');
# =======
# console.log('Hello from Feature A');
# >>>>>>> feature-a

# 3. Resolve manually
# console.log('Hello from Main and Feature A');

# 4. Save file and mark as resolved
git add app.js
git commit -m "Resolve merge conflict in app.js"

# Alternative: Abort merge
git merge --abort

Advanced Conflict Resolution

# Use merge tools
git mergetool

# Set conflict resolution strategies
git merge -X theirs feature-branch  # prefer their version
git merge -X ours feature-branch     # prefer our version

# Octopus merge (multiple branches at once)
git merge branch1 branch2 branch3

# Subtree merge (integrate external project)
git subtree add --prefix=external-repo https://github.com/user/repo.git main

Git Workflows

1. Centralized Workflow

# Simplest workflow
# Everyone works directly on main

# 1. Local changes
git add .
git commit -m "Add new feature"

# 2. Upload changes
git push origin main

# 3. Resolve conflicts (if any)
git pull origin main
# Resolve conflicts
git push origin main

2. Feature Branch Workflow

# Each feature gets its own branch

# 1. Create feature branch
git checkout main
git pull origin main
git checkout -b feature-user-profile

# 2. Work on feature
git add .
git commit -m "Add user profile page"
git push origin feature-user-profile

# 3. Create pull request
# Via GitHub/GitLab UI or CLI

# 4. Review and merge
# Code review by team members
# Merge into main after approval

# 5. Clean up branch
git checkout main
git pull origin main
git branch -d feature-user-profile

3. Gitflow Workflow

# Gitflow with main, develop, feature, release, hotfix branches

# 1. Initialize develop branch
git checkout main
git checkout -b develop
git push origin develop

# 2. Feature branch from develop
git checkout develop
git checkout -b feature-shopping-cart

# 3. Merge feature into develop
git checkout develop
git merge feature-shopping-cart
git push origin develop

# 4. Create release branch
git checkout develop
git checkout -b release/v1.0.0

# 5. Merge release into main and develop
git checkout main
git merge release/v1.0.0
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin main --tags

git checkout develop
git merge release/v1.0.0
git push origin develop

# 6. Hotfix from main
git checkout main
git checkout -b hotfix/critical-bug
# Fix bug
git checkout main
git merge hotfix/critical-bug
git checkout develop
git merge hotfix/critical-bug

4. Forking Workflow

# For open source projects or external contributions

# 1. Fork repository (via GitHub/GitLab UI)
# 2. Clone your own repository
git clone https://github.com/yourusername/project.git
cd project

# 3. Add upstream remote
git remote add upstream https://github.com/original/project.git

# 4. Create feature branch
git checkout -b feature-new-functionality

# 5. Commit changes
git add .
git commit -m "Add new functionality"

# 6. Push to your own repository
git push origin feature-new-functionality

# 7. Create pull request to original repository

# 8. Regularly update upstream
git fetch upstream
git checkout main
git merge upstream/main

Advanced Git Techniques

Rebase and Interactive Rebase

# Simple rebase
git checkout feature-branch
git rebase main

# Interactive rebase (reorder/edit commits)
git rebase -i HEAD~3

# Interactive rebase options:
# pick: Keep commit unchanged
# reword: Change commit message
# edit: Edit commit
# squash: Merge with previous commit
# fixup: Merge with previous commit (without message)
# drop: Remove commit

# Example of interactive rebase
# pick 1234567 Add feature A
# squash 2345678 Add feature B
# reword 3456789 Fix typo

# Force rebase (be careful!)
git push --force-with-lease origin feature-branch

Git Hooks

# Hooks in .git/hooks/
# Pre-commit hook (before every commit)
#!/bin/sh
# .git/hooks/pre-commit
echo "Running pre-commit checks..."
npm run lint
npm run test

# Pre-push hook (before every push)
#!/bin/sh
# .git/hooks/pre-push
echo "Running pre-push tests..."
npm run test:coverage

# Enable hooks (make executable)
chmod +x .git/hooks/pre-commit
chmod +x .git/hooks/pre-push

# Set up hooks globally
git config --global init.templatedir '~/.git-templates'

Git Submodules

# Add submodule
git submodule add https://github.com/user/library.git libs/library

# Initialize submodule
git submodule init
git submodule update

# Clone submodule with --recurse-submodules
git clone --recurse-submodules https://github.com/user/project.git

# Update submodule
git submodule update --remote

# Remove submodule
git rm --cached libs/library
rm -rf libs/library
git commit -m "Remove submodule"

Best Practices

Commit Messages

# Good commit messages
feat: Add user authentication system
fix: Resolve memory leak in data processing
docs: Update API documentation
style: Format code according to style guide
refactor: Simplify database connection logic
test: Add unit tests for user service
chore: Update dependencies

# Structure: <type>(<scope>): <description>
# Types: feat, fix, docs, style, refactor, test, chore

# Detailed commit message
feat(auth): Add OAuth2 integration

- Add Google OAuth provider
- Implement token refresh mechanism
- Add user profile synchronization

Closes #123

Branch Naming Conventions

# Good branch names
feature/user-authentication
bugfix/memory-leak-fix
hotfix/critical-security-patch
release/v1.2.0
docs/update-api-documentation
refactor/database-connection-pool
test/add-unit-tests

# Bad branch names
fix-stuff
new-feature
branch-1
temp

Repository Structure

# .gitignore
# Compiled files
*.class
*.jar
*.war
*.ear

# IDE files
.idea/
.vscode/
*.swp
*.swo

# Dependencies
node_modules/
target/
build/

# Logs
*.log
logs/

# Environment files
.env
.env.local

# .gitattributes
# Text files
*.txt text
*.md text
*.js text
*.java text

# Binary files
*.jpg binary
*.png binary
*.pdf binary

# Line endings
* text=auto eol=lf

Troubleshooting and Problem Solving

Common Issues

# 1. Wrong commit in wrong branch
git checkout correct-branch
git cherry-pick <wrong-commit-hash>
git checkout wrong-branch
git reset --hard HEAD~1

# 2. Recover lost commits
git reflog
git checkout -b recovery <commit-hash>

# 3. Reset unwanted changes
git reset --hard HEAD
git reset --hard HEAD~1  # Remove last commit
git clean -fd            # Remove untracked files

# 4. Remote repository issues
git remote -v
git remote set-url origin https://github.com/user/new-repo.git

# 5. Restore push after force-push
git reflog
git reset --hard HEAD@{1}
git push --force-with-lease origin main

Performance Optimization

# Optimize repository
git gc --prune=now

# Find large files
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort --numeric-sort --key=2 | tail -10

# Git LFS for large files
git lfs install
git lfs track "*.psd"
git lfs track "*.zip"
git add .gitattributes
git commit -m "Track large files with Git LFS"

Git in Practice

CI/CD Integration

# .github/workflows/ci.yml
name: CI Pipeline

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v2
    
    - name: Setup Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '16'
        
    - name: Install dependencies
      run: npm ci
      
    - name: Run tests
      run: npm test
      
    - name: Run linting
      run: npm run lint
      
    - name: Build project
      run: npm run build

Git for Team Collaboration

# Team guidelines
# 1. Use feature branches
# 2. Pull requests for code review
# 3. Automatic tests on every push
# 4. Protected branches for main and develop
# 5. Regular rebase instead of merge

# Example of protected branch setup
# Via GitHub/GitLab:
# - Require pull request reviews before merging
# - Require status checks to pass before merging
# - Require branches to be up to date before merging
# - Include administrators as reviewers

Exam-Relevant Concepts

Important Git Commands

CommandDescriptionUsage
git initInitialize repositoryStart new project
git cloneClone repositoryCopy existing project
git addAdd changes to stagingPrepare changes
git commitCommit changesSave local changes
git pushUpload changesSynchronize with remote
git pullDownload changesAdopt remote changes
git branchManage branchesCreate development lines
git mergeMerge branchesIntegrate changes
git rebaseRebase branchesCreate linear history

Typical Exam Tasks

  1. Explain Git workflows
  2. Resolve merge conflicts
  3. Implement branch strategies
  4. Use advanced Git commands
  5. Set up CI/CD with Git

Summary

Git is essential for modern software development:

  • Distributed system: Every developer has complete copy
  • Branches: Parallel development without conflicts
  • Merge: Intelligent merging of changes
  • Workflows: Structured team collaboration
  • CI/CD: Automation of build and deployment

Good Git management requires discipline, clear rules, and regular maintenance of the repository.

Back to Blog
Share:

Related Posts