Converted EPUB: Mastering Git
Mastering Git
Attain expert-level proficiency with Git by mastering distributed version contro
Jakub Nar■bski
Mastering Git
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retriev
Every effort has been made in the preparation of this book to ensure the accurac
Packt Publishing has endeavored to provide trademark information about all of th
Group Product Manager: Preet Ahuja
Publishing Product Manager: Vidhi Vashisth
Book Project Manager: Ashwini Gowda
Senior Editor: Roshan Ravi Kumar
Table of Contents
Preface
Part 1 - Exploring Project History and Managing Your Own Work
1
Git Basics in Practice
Technical requirements
A brief introduction to version control and Git
Git by example
Setup and initialization
Collaborative development
Branching and merging
Summary
Questions
Answers
Further reading
Preface
Git is the most popular open source and distributed version-control system. Vers
Mastering Git will help novice Git professionals attain expert-level proficiency
This book is meticulously designed to help you gain deeper insights into Git’s a
You’ll begin with a quick example of using Git for the collaborative development
Version control topics are accompanied by detailed descriptions of the relevant
Who this book is for
If you are a Git user with a reasonable knowledge of it and you are familiar wit
If you are a system administrator, project lead, or operations manager, this boo
A basic knowledge of installing Git and its software configuration management co
What this book covers
Chapter 1, Git Basics in Practice, serves as a reminder of the version-control b
Chapter 2, Developing with Git, shows how to selectively commit files and intera
Chapter 3, Managing Your Worktrees, teaches you how to manage your files in deta
Chapter 4, Exploring Project History, introduces the concept of a graph of revis
Part 1 - Exploring Project History and Managing Your Own Work
In this part, you will start by understanding the basics of using Git in a simpl
This part has the following chapters:
Chapter 1, Git Basics in Practice
Chapter 2, Developing with Git
Chapter 3, Managing Your Worktrees
Chapter 4, Exploring Project History
Chapter 5, Searching Through the Repository
1
Git Basics in Practice
This book is intended for intermediate and advanced Git users to help them on th
This chapter will serve as a reminder of version control basics with Git. The fo
In this chapter, we will cover the following:
A brief introduction to version control and Git
Setting up a Git environment and Git repository (init and clone)
Adding files, checking status, creating commits, and examining the history
Interacting with other Git repositories (pull and push)
Creating and listing branches, switching to a branch, and merging changes
Resolving a simple merge conflict
Creating and publishing a tag
Technical requirements
2
Developing with Git
This chapter will describe how to create new revisions and new lines of developm
Here, we will focus on committing one’s own work on the solo development. The de
This chapter will introduce the very important Git concept of the staging area (
The following is the list of the topics we will cover in this chapter:
The index — a staging area for commits
Examining the status of the working area, and changes in it
How to read the extended unified diff that is used to describe changes
Selective and interactive commit, and amending a commit
Creating, listing, renaming, and switching to branches, and listing tags
What can prevent switching branches, and what you can do then
Rewinding a branch with git reset
Detached HEAD — that is, the unnamed branch (for example, a result of checking o
3
Managing Your Worktrees
The previous chapter, Developing with Git, described how you can use Git for pro
The previous chapter also taught you how to examine changes. In this chapter, yo
This chapter will cover the following topics:
Ignoring files – marking files as intentionally not being under version control
File attributes – path-specific configuration
Using various modes of the git reset command
Stashing away your changes to handle interruptions
Managing the working directory’s contents and the staging area
Multiple working directories (worktrees)
Ignoring files
The files inside your working area (also known as the worktree) can be tracked o
Splitting a commit in two with reset
You can use a mixed reset to split a commit in two. First, run git reset HEAD^ t
If it is easier to interactively remove changes, that’s also an option. Use git
Here, again, like for squashing commits, you can use the interactive rebase to s
Saving and restoring state with the WIP commit
Suppose you are interrupted by an urgent bugfix request while you are in the mid
$ git commit -a -m 'snapshot WIP (Work In Progress)'
Then, you can handle the interruption, switching to the maintenance branch and c
$ git switch -
$ git reset --soft HEAD^
$ git reset
Usually, though it is much easier to just use git stash instead to handle interr
Discarding changes and rewinding the branch
4
Exploring Project History
One of the important parts of mastering a version control system (VCS) is explor
In this chapter, you will learn how to select and view a revision or a range of
This chapter will also introduce the concept of Directed Acyclic Graph (DAG) of
Here is the list of topics we will cover in this chapter:
DAG of revisions as a way of representing history
Different ways of revision selection
Selecting starting branches and tags
Using data from reflog to select revisions
Double-dot (A..B) and triple-dot notation (A…B) for revision range selection
Advanced revision range selection
The purpose of this chapter is to teach you how to select relevant parts of proj
5
Searching Through the Repository
After selecting the parts of the project history that you want to search, the ne
Another important skill is to format Git output so that it is easy to find the i
Here is the list of topics we will cover in this chapter:
Limiting the history and history simplification
Searching the history with the pickaxe tool and diff search
Finding bugs with git bisect
Line-wise history of file contents with git blame and rename detection
Selecting and formatting output (the pretty formats)
Summarizing contribution with git shortlog
Specifying a canonical author name and email with .mailmap
Viewing specific revisions, files at revision, and diff output options
Part 2 - Working with Other Developers
In this part, you will learn how to choose the correct workflow for you (which i
This part has the following chapters:
Chapter 6, Collaborative Development with Git
Chapter 7, Publishing Your Changes
Chapter 8, Advanced Branching Techniques
Chapter 9, Merging Changes Together
Chapter 10, Keeping History Clean
6
Collaborative Development with Git
Chapter 2, Developing with Git, and Chapter 3, Managing Your Worktrees, taught y
This chapter and Chapter 7, Publishing Your Changes, present a bird’s-eye view o
This chapter describes different collaborative workflows, explaining the advanta
The following topics will be covered in this chapter:
Centralized and distributed workflows, and bare repositories
Managing remotes and one-off single-shot collaboration
How versions are addressed—the chain of trust
Tagging; lightweight tags versus signed tags
Signed tags, signed merges, and signed commits
Collaborative workflows
There are various levels of engagement while using a version control system. One
7
Publishing Your Changes
Chapter 6, Collaborative Development with Git (the previous chapter), taught you
In this chapter, you will find out how you can exchange information between your
This chapter will also teach you how to provide your changes upstream, so that t
This chapter will cover the following topics:
Transport protocols used by Git and their advantages and disadvantages
Managing credentials (passwords, keys) for remote repositories
Publishing changes: push and pull requests, and exchanging patches
Using bundles for offline transfer and speeding up the initial clone
Remote transport helpers and their use
Transport protocols and remote helpers
In general, URLs in the configuration of remote repository contain information a
8
Advanced Branching Techniques
Chapter 6, Collaborative Development with Git, described how to arrange teamwork
This chapter will dive deeper into the details of collaboration in distributed d
You will also learn branching techniques: how branches can be used to create new
In this chapter, we will cover the following topics:
Different kinds of branches, both long-lived and short-lived, and their purpose
Various branching patterns, and how they can be composed into workflows
Release engineering for different branching models
Using branches to fix a security issue in more than one released version
Remote-tracking branches and refspecs
Rules for fetching and pushing branches and tags
Selecting a push mode to fit the chosen collaboration workflow
The graduation branches workflow
To be able to provide a stable line of the product, and to be able to test it in
Besides keeping stable and unstable development separate, there is also a need f
Here, simple enough means that you can just create the next major release out of
In such a situation, you would have at least three integration branches. There w
Figure 8.3 – The graduation or progressive-stability branches workflow. You sho
You can use this workflow as-is, with only graduation branches, and no other typ
You commit bug fixes on the maintenance branch and merge it into the stable bran
You create revisions with the well-tested work on the stable branch, merging it
9
Merging Changes Together
The previous chapter, Advanced Branching Techniques, described how to use branch
This chapter will teach you how to integrate changes from different parallel lin
In this chapter, we will cover the following topics:
Merging, merge strategies, and merge drivers
Cherry-picking and reverting a commit
Applying a patch and a patch series
Rebasing a branch and replaying its commits
A merge algorithm at file and contents level
Three stages in the index
Merge conflicts – how to examine and resolve them
Reusing recorded [conflict] resolutions with git rerere
An external tool – git-imerge
10
Keeping History Clean
The previous chapter, Merging Changes Together, described how to join changes de
This chapter will answer all those questions. It will explain why one might want
To really understand some of the topics presented here, and to truly master thei
In this chapter, we will cover the following topics:
The basics of the object model of Git repositories
Why you shouldn’t rewrite published history, and how to recover from doing so
The interactive rebase: reordering, squashing, splitting, and testing commits
Large-scale scripted history rewriting
Reverting a revision, reverting a merge, and re-merging after a reverted merge
Amending history without rewriting with replacements
Appending additional information to objects with notes
The consequences of upstream rewrites
Now you will see, in a simple example, the perils of rewriting published history
Figure 10.2 – The state of the local repository of a downstream developer before
Then, the upstream developer rewrites the subsys branch to start from the curren
Figure 10.3 – The state of a public upstream repository after rewrite, with an e
Part 3 - Managing, Configuring, and Extending Git
This part describes how to manage Git, how to customize and extend it, and how t
This part has the following chapters:
Chapter 11, Managing Subprojects
Chapter 12, Managing Large Repositories
Chapter 13, Customizing and Extending Git
Chapter 14, Git Administration
Chapter 15, Git Best Practices
11
Managing Subprojects
In Chapter 6, Collaborative Development with Git, we learned how to manage multi
This chapter will explain and show different ways to connect different subprojec
In this chapter, we will cover the following topics:
Managing library and framework dependencies
Dependency management tools: managing dependencies outside of Git
Importing code into a superproject as a subtree
Using subtree merges; the git-subtree and git-stree tools
Nested repositories (submodules): a subproject inside a superproject
Internals of submodules: gitlinks, .gitmodules, and the .git file
Use cases for subtrees and submodules; comparison of approaches
Alternative third-party solutions and tools/helpers
12
Managing Large Repositories
Because of its distributed nature, Git includes the full change history in each
But what happens when the repository you want to work on is huge? Can we avoid t
If you think about it, there are broadly three main reasons for repositories to
Submodules (presented in the previous chapter, Managing Subprojects) are sometim
In this chapter, we will cover the following topics:
Git and large files
Handling repositories with a very long history with a shallow clone
Storing large binary files in a submodule or outside the repository
Reducing the size of the working directory with sparse checkout
How to make a local repository smaller with a sparse clone
Which operations will require network access in different variants of sparse clo
Faster operations with filesystem monitor
13
Customizing and Extending Git
Earlier chapters were designed to help you understand how Git works and master G
This chapter will cover configuring and extending Git to fit one’s needs. First,
Then this chapter will cover how to automate Git with hooks, describing for exam
Many issues, such as gitattributes, remote and credential helpers, and the basic
In this chapter, we will cover the following topics:
Setting up the shell prompt and Tab completion for a command line
Types and examples of graphical user interfaces
Configuration files and basic configuration options
Installing and using various types of hooks
Simple and complex aliases
Extending Git with new commands and helpers
Command-line options and environment variables
Git processes the switches that change its behavior in a hierarchical fashion, f
The most specific one, overriding all the others, is the command-line options. T
Important note
One issue to note is that some command-line options, for example, --no-pager or
$ git --no-replace-objects log -5 --oneline --graph --decorate
You can find the conventions used through the Git command-line interface on the
The second way to change how the Git command works is to use environment variabl
Git also makes use of some nonspecific environment variables. These are meant as
Git configuration files
The final way to customize how Git works is with the configuration files. In man
Git uses a series of configuration files to determine non-default behavior that
Tip
You can also read the values from any blob with configuration-like contents; for
The first place Git looks for configuration is the system-wide configuration fil
Installing a Git hook
The hooks in Git are executable programs (usually scripts), which are stored in
Hook programs are each named after the event that triggers them. This means that
When you initialize a new repository with git init (this is done also while usin
A template for repositories
Sometimes you would want to have the same set of hooks for all your repositories
Also, the alternative directory with the repository creation templates can be gi
Note, however, that this mechanism has some limitations. As the files from the t
Hook management tools
Maintaining hooks for a team of developers can be tricky. There are many tools a
Client-side hooks
There are quite a few client-side hooks. They can be divided into the commit-wor
Important note
It is important to note that hooks are not copied when you clone a repository. T
Commit process hooks
14
Git Administration
The previous chapter, Customizing and Extending Git, among other things, explain
The earlier chapters helped master your work with Git as a developer, as a team
This chapter is intended to help those of you who are in a situation of dealing
In this chapter, we will cover the following topics:
Server-side hooks – implementing a policy and notifications
How to set up Git on a server
Third-party tools to manage remote repositories
Signed pushes to assert updating refs and enable audits
Reducing the size of hosted repositories with alternates and namespaces
Improving server performance and helping the initial clone
Checking for repository corruption and fixing a repository
Recovering from errors with the help of reflogs and git fsck
15
Git Best Practices
The last chapter of Mastering Git presents a collection of generic and Git-speci
This chapter will cover the issues of managing the working directory, creating c
In this chapter, we will cover the following topics:
How to separate projects into repositories
What types of data to store in a repository and which files Git should ignore
What to check before creating a new commit
How to create a good commit and a good commit series (or, in other words, how t
How to choose an effective branching strategy, and how to name branches and tag
How to review changes and how to respond to the review
Starting a project
When starting a project, you should choose and clearly define a project governan
Index
As this ebook edition doesn't have fixed pagination, the page numbers below are
Symbols
.gitattributes files 66
.gitignore file 63
A
amend 248
ancestry 107
annotated tags 16, 47, 157
applypatch-msg hook 356
Ask 204
attribute macro 76
authentication domain 175
author
versus committer 131
graphical history viewer 336
graphical user interfaces (GUIs) 330
H
healthy branch 188
hierarchical (dictator-and-lieutenants) workflow 148, 149
pros and cons 149
hierarchical branch name 394
hook-based file system monitor 326
hooks 353
Git, automating with 353
used, for implementing Git-enforced policy 376
hooks, for applying patches from emails
applypatch-msg hook 356
post-applypatch hook 357
pre-applypatch hook 357
packtpub.com
Subscribe to our online digital library for full access to over 7,000 books and
Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos f
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF
At www.packtpub.com, you can also read a collection of free technical articles,
Other Books You May Enjoy
If you enjoyed this book, you may be interested in these other books by Packt: