Advanced Git & GitHub for DevOps Engineers - Part 1

Advanced Git & GitHub for DevOps Engineers - Part 1

Git and GitHub are essential tools for DevOps engineers, enabling them to effectively manage code changes, facilitate collaboration, and maintain code integrity. In this blog post, we'll delve into advanced Git concepts, including branching, reverting, resetting, rebasing, and merging, providing clear explanations, examples, and commands to enhance your Git expertise.

1. Git Branching

Git branching allows you to create separate lines of development within a repository, enabling you to experiment with new features or bug fixes without affecting the main codebase.

Creating a Branch:

git branch <branch_name>

Switching Branches:

git checkout <branch_name>

Merging Branches:

git merge <branch_name>

2. Git Revert and Reset

2.1 Git Revert

Git revert creates a new commit that undoes the changes made in a previous commit, effectively reverting those changes without altering the commit history.

Reverting a Commit:

git revert <commit_hash>

2.2 Git Reset

Git reset moves the HEAD pointer to a specific commit, effectively discarding any commits that come after that point.

Resetting to a Commit:

git reset <commit_hash>

2.3 Difference between Git Revert and Git Reset

Git revert is a non-destructive operation that creates a new commit, while git reset is a destructive operation that discards commits. Git revert is generally used to undo changes in public branches, while git reset is typically used for private branches.

3. Git Rebase and Merge

3.1 Git Rebase

Git rebase reapplies a series of commits onto a different branch, effectively rewriting the commit history.

Rebasing a Branch:

git rebase <target_branch>

3.2 Git Merge

Git merge combines the changes from two branches into a single branch.

Merging a Branch:

git merge <branch_name>

Example: Rebase vs. Merge

Consider two branches, develop and feature. You've made commits on the feature branch and want to integrate those changes into the develop branch.

Rebase:

  1. Switch to the feature branch: git checkout feature

  2. Rebase onto the develop branch: git rebase develop

  3. Resolve any conflicts that arise

  4. Push the updated feature branch: git push origin feature

Merge:

  1. Switch to the develop branch: git checkout develop

  2. Merge the feature branch: git merge feature

  3. Resolve any conflicts that arise

  4. Push the updated develop branch: git push origin develop

In general, rebasing is preferred when you want a clean linear commit history, while merging is suitable when you want to preserve the complete history of each branch.