Managing Your Worktrees
local graph
Chapter 3 — Managing Your Worktrees
Section titled “Chapter 3 — Managing Your Worktrees”The previous chapter, Developing with Git, described how you can use Git for project development, including how to create new revisions. In this chapter, we will focus on learning how to manage a working directory (worktree) so that you can prepare content for a new commit. This chapter will teach you how to manage your files in detail. It will also show you how to care for files that require special handling while introducing the concepts of ignored files and file attributes. Then, you will learn how to fix mistakes in handling files, both in the working directory and in the staging area, as well as how to fix or split the latest commit. Finally, you will learn how to safely handle interruptions in the workflow with stashes and multiple working directories.
The previous chapter also taught you how to examine changes. In this chapter, you will learn how to undo and redo those changes selectively, as well as how to view different versions of a file.
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
gitresetcommand - Stashing away your changes to handle interruptions
- Managing the working directory’s contents and the staging area
- Multiple working directories (worktrees)
Ignoring files
Section titled “Ignoring files”The files inside your working area (also known as the worktree) can be tracked or untracked by Git. Tracked files, as the name suggests, are those files whose changes Git will follow. For Git, if a file is present in the staging area (also known as the index), it will be tracked, and – unless specified otherwise – it will be a part of the next revision. You add files to be tracked, to have them as a part of the project history.
The purpose of the staging area
The index, or the staging area, is used not only for Git to know which files to track, but also as a kind of scratchpad to create new commits, as described in Chapter 2, Developing with Git, and to help resolve merge conflicts, as shown in Chapter 9, Merging Changes Together.
Often, you will have some individual files or a class of files that you never want to be a part of the project history, and never want to track. These can be your editor backup files, or automatically generated files that are produced by the project’s build system (executables, object files, minified sources, source maps, and so on).
You don’t want Git to automatically add such files, for example, when doing bulk add with git add :/ (adding the entire working tree) or with git add . (adding the current directory), or when updating the index to the worktree’s state with git add --all.
Quite the opposite: you want Git to actively prevent you from accidentally adding them. You also want such files to be absent from the git status output as there can be many of them. They could otherwise drown out legitimate new unknown files there. You want such files to be intentionally untracked – that is, ignored.
Un-tracking and re-tracking files
If you want to start ignoring a file that was formerly tracked, such as when you’re moving from a hand-generated HTML file to using a lightweight markup language such as Markdown instead, you usually need to un-track the file without removing it from the working directory while adding it to the list of ignored files. You can do this with git rm --cached <file> (as shown in the output of git status). This command removes the named file from the staging area.
To add (start tracking) an intentionally untracked (that is, ignored) file, you need to use git add --force <file>, as Git will tell you.
Marking files as intentionally untracked (ignored)
Section titled “Marking files as intentionally untracked (ignored)”If you want to mark a file or a set of files as intentionally ignored, you need to add a shell glob pattern that matches files that you want to have ignored by Git to one of the following gitignore files, one pattern per line:
- The per-user file, which can be specified by the
core.excludesFileconfiguration variable. If this configuration variable is not set, then the default value of$XDG_CONFIG_HOME/git/ignoreis used. This, in turn, defaults to$HOME/.config/git/ignoreif the$XDG_CONFIG_HOMEenvironment variable is not set or empty (where$HOMEis the current user’s home directory). - The per-local repository
$GIT_DIR/info/excludefile in the administrative area of the local clone of the repository (in most cases,$GIT_DIRpoints to the.git/directory in the top-level directory of the project). - The
.gitignorefiles in the working directories of a project. These are usually tracked, and in this case, they are shared among all developers.
Some commands, such as git clean, also allow us to specify ignore patterns from a command line with the -- exclude=<pattern> option.
When deciding whether to ignore a path, Git checks all those sources in the order specified in the preceding list, with the last matching pattern deciding the outcome. The .gitignore files are checked in order, starting from the top directory of the project down to the directory of files to be examined.
To make .gitignore files more readable, you can use blank lines to separate groups of files (a blank line matches no files). You can also describe patterns or groups of patterns with comments; a line starting with the hash character, #, serves as one (to ignore a pattern beginning with #, escape the first hash character with a backslash, \ – for example, \#*#). Trailing spaces (at the end of the line) are ignored unless escaped with a backslash, \.
Each line in the .gitignore file specifies a Unix glob pattern, a shell wildcard. The * wildcard matches zero or more characters (any string), while the ? wildcard matches any single character. You can also use character classes with brackets, [...]. Take, for example, the following list of patterns:
*.[oa]*~Here, the first line tells Git to ignore all files with the .a or .o extension – *.a files are archive files (for example, a static library), and *.o files are object files that may be the products of compiling your code. The second line tells Git to ignore all files ending with a tilde, ~; this is used by many Unix text editors to mark temporary backup files.
If the pattern does not contain a slash, /, which is a path component separator, Git treats it as a shell glob and checks the filename or directory name for a match, starting at the appropriate depth (this means the .gitignore file location if the pattern is in such a file, or the top level of the repository otherwise). The exception is patterns ending with a slash, /, which is used to have the pattern only matched against directories but otherwise treated as if the trailing slash was removed.
A leading slash matches the beginning of the pathname. This means the following:
- Patterns not containing a slash match everywhere in the repository; we can say that the pattern is recursive.
For example, the
*.opattern matches object files anywhere, both at the.gitignorefile level and in subdirectories such asfile.o,obj/file.o, and others. - Patterns ending with a slash only match directories but are otherwise recursive (unless they contain other slashes).
For example, the
auto/pattern will match both the top-levelautodirectory and thesrc/autodirectory but will not match theautofile (or a symbolic link either). - To anchor a pattern and make it non-recursive, add a leading slash.
For example, the
/TODOpattern will match and make Git ignore the current-levelTODOfile, but not files in subdirectories, such assrc/TODO. - Patterns containing a slash inside are anchored and non-recursive, and wildcard characters (
*,?, or a character class such as[ao]) do not match the directory separator that is the slash,/. If you want the pattern to match any number of directories, use two consecutive asterisks,**, in place of the path component (which means**/foo,foo/**, andfoo/**/bar). For example,doc/*.htmlmatches thedoc/index.htmlfile but notdoc/api/index.html; to match HTML files anywhere inside thedocdirectory, you can use thedoc/**/*.htmlpattern (or put the*.htmlpattern in thedoc/.gitignorefile).
You can also negate a pattern by prefixing it with an exclamation mark, !; any matching file excluded by the earlier rule is then included (non-ignored) again. For example, to ignore all generated HTML files, but include the one HTML file generated by hand, you can put the following in the .``gitignore file:
# ignore html files, generated from AsciiDoc sources*.html# except for the files below which are generated by hand!welcome.htmlNote
For performance reasons, Git doesn’t go into excluded directories, and (up until Git 2.7) this means that you cannot re-include a file if a parent directory is excluded.
This means that to ignore everything except for the subdirectory, you need to write the following:
# exclude everything except directory t0001/bin/*!/t0001/t0001/*!/t0001/binTo match a pattern beginning with !, escape it with a backslash, similar to what you need to do for the # character – for example, use the \!important!.md pattern to match the file named !important!.md.
Which types of files should be ignored?
Section titled “Which types of files should be ignored?”Now that we know how to mark files as intentionally untracked (ignored), there is the question of which files (or classes of files) should be marked as such. Another issue is where we should add a pattern for ignoring specific types of files – that is, in which of the three types of .``gitignore files.
The first rule is that you should never track automatically generated files (usually generated by the build system of a project). If you add such files to the repository and if you track them, there is a high chance that they will get out of sync with their source. Besides, they are not necessary, as you can always re-generate them. The only possible exception is generated files where the source rarely changes and generating them requires extra tools that developers might not have (if the source changes more often, you can use an orphan branch to store these generated files and refresh this branch only at release time; see Chapter 2, Developing With Git, the Creating orphan branches section for more information).
Those automatically generated files are the files that all developers will want to ignore. Therefore, they should go into a tracked .gitignore file. This list of patterns will be version-controlled and distributed to other developers via a clone; this way, all developers will get it. You can find a collection of useful .gitignore templates for different programming languages at https://github.com/github/gitignore, or you can use the web app at https://gitignore.io.
Second, there are temporary files and byproducts specific to one user’s toolchain; those should usually not be shared with other developers. If the pattern is specific to both the repository and the user – for example, auxiliary files that live inside the repository but are specific to the workflow of a user (for example, to the IDE used for the project) – it should go into the per-clone $ GIT_DIR/info/exclude file.
Patterns that the user wants to ignore in all situations and are not specific to the repository (or to the project) should generally go into a per-user .gitignore file specified by the core.excludesFile config variable, set in the per-user (global) ~/.gitconfig config file (or ~/.config/git/config). This is usually ~/.config/git/ignore by default.
Important note about the per-user.gitignore file
The per-user ignore file cannot be ~/.gitignore as this would be the in-repository .gitignore file for the versioned user’s home directory if the user wants to keep the ~/ directory ($HOME) under version control.
This is the place where you can put patterns that match the backup or temporary files generated by your editor or IDE of choice.
Ignored files are considered expendable
Warning: Do not add precious files – that is, those you do not want to track in a given repository but whose contents are important – to the list of ignored files! The types of files that are ignored (excluded) by Git are either easy to regenerate (build products and other generated files) or not important to the user (temporary or backup files).
Therefore, Git considers ignored files expendable and will remove them without warning when required to do a requested command – for example, if the ignored file conflicts with the contents of the revision being checked out.
Listing ignored files
Section titled “Listing ignored files”You can list untracked ignored files by appending the --ignored option to the git status command:
$ git status --ignoredOn branch masterIgnored files: (use "git add -f <file>..." to include in what will be committed) rand.c~no changes added to commit (use "git add" and/or "git commit -a")$ git status --short --branch --ignored## master!! rand.c~Instead of using git status --ignored, you can use the dry-run option of cleaning ignored files, git clean -Xnd, or the low-level (plumbing) git ls-files command:
$ git ls-files --others --ignored --exclude-standardrand.c~The latter command can also be used to list tracked files that match ignore patterns. If there are any such files, it might mean that some files need to be un-tracked (perhaps because what was once a source file is now generated), or that ignore patterns are too broad. Since Git uses the existence of a file in the staging area (cache) to know which files to track, this can be done with the following command:
$ git ls-files --cached --ignored --exclude-standardAn empty result, like what’s shown here, means that everything is fine.
Plumbing versus porcelain commands
Git commands can be divided into two sets: high-level porcelain commands intended for interactive usage by the end user and low-level plumbing commands intended mainly for shell scripting. The major difference is that high-level commands have outputs that can change and are constantly improving. For example, the output of the git branch command in the detached HEAD case changed from (no branch) to (detached from HEAD). Their output and behavior are also subject to the configuration. Note that some porcelain commands have the option to switch to unchanging output via --porcelain.
Another important difference is that plumbing commands try to guess what you meant, they have default parameters, use the default configuration, and so on. This isn’t the case with plumbing commands. You need to pass the --exclude-standard option to the git ls-files command to make it respect the default set of ignore files.
You can find more on this topic in Chapter 13, Customizing and Extending Git.
Trick – ignoring changes in tracked files
Section titled “Trick – ignoring changes in tracked files”You might have files in your repository that are changed but rarely committed. These can be various local configuration files that are edited to match the local setup but should never be committed upstream. This can be a file containing the proposed name for a new release, to be committed later when tagging the next released version.
You would want to keep such files in a dirty state most of the time, but you would like Git not to tell you about their changes all the time in case you miss other changes because you’re used to ignoring such messages.
Dirty working directory
The working directory is considered clean if it is the same as the committed and staged version and dirty if any modifications or changes have been made.
Git can be configured – or rather tricked in this case – to skip checking the worktree (to assume that it is always up to date), and to use the staged version of the file instead. This can be done by setting the aptly named skip-worktree flag for a file. For this, you would need to use the low-level git update-index command, which is the plumbing equivalent of the user-facing git add porcelain. You can check file status and flags with git ls-files, which will use the letter S for files with this flag set:
$ git update-index --skip-worktree GIT-VERSION-NAME$ git ls-files -vS GIT-VERSION-NAMEH …Note that this elision of the worktree also includes the git stash command; to stash away your changes and make the working directory clean, you need to disable this flag (at least temporarily). To make Git look at the working directory version and start tracking changes to the file, use the following command:
$ git update-index --no-skip-worktree GIT-VERSION-NAMEThis problem is caused by the fact that this use of the skip-worktree flag is not intended use; this flag was created to manage so-called sparse checkout – more on that in Chapter 12, Managing Large Repositories.
Important note
There is a similar assume-unchanged flag that can be used to make Git completely ignore any changes to the file, or rather assume that it is unchanged. Files marked with this flag never show as changed in the output of the git status or git diff command. The changes to such files will not be staged, nor committed.
This is sometimes useful when you’re working with a big project on a filesystem that’s very slow at checking for changes. However, do not use assume-unchanged to ignore changes to tracked files. You are promising that the file didn’t change, lying to Git. This means, for example, that with git stash save believing what you stated, you would lose your precious local changes.
File attributes
Section titled “File attributes”There are some settings and options in Git that can be specified on a per-path basis, similar to how ignoring files (marking files as intentionally untracked) works. These path-specific settings are called attributes.
To specify attributes for files matching a given pattern, you need to add a line with a pattern, separated by a space and followed by a whitespace-separated list of attributes, to one of the .gitattributes files (similar to how .gitignore files work):
- The per-user file, for attributes that should affect all repositories for a single user, specified by the
core.attributesFileconfiguration variable. By default, this is~/.config/git/attributes - The per-repository
.git/info/attributesfile in the administrative area of the local clone of the repository, for attributes that should only affect a single specific clone of the repository (for one user’s workflow). - The
.gitattributesfiles in the working directories of a project, for those attributes that should be shared among developers.
The rules for how patterns are used to match files are the same as for the .gitignore files, as described previously, except that there is no support for negative patterns, and that patterns matching the directory do not recursively match paths inside that directory.
Each attribute can be in one of the following states for a given path: set (special value true), unset (special value false), set to a given value, or unspecified:
pattern* set -unset set-to=value !unspecifiedNote
There can be no whitespace around the equals sign, =, when setting an attribute to a string value!
When more than one pattern matches the path, a later line overrides an earlier line on a per-attribute basis. .gitattributes files are used in order, from the per-user, through per-repository, to the .gitattributes file in a given directory, like for .``gitignore files.
Identifying binary files and end-of-line conversions
Section titled “Identifying binary files and end-of-line conversions”Different operating systems and different applications can differ in how they represent newlines in text files. Unix and Unix-like systems (including Mac OS X) use a single control character LF (\n), while Windows uses CRLF – that is, CR followed by LF (\n\r); macOS up to version 9 used CR alone (\r).
That might be a problem for developing portable applications if different developers use different operating systems. We don’t want to have spurious changes because of different end-of-line conventions. Therefore, Git makes it possible to automatically normalize end-of-line characters to be LF in the repository on commit (check-in), and optionally to convert them to CR + LF in the working directory on checkout.
You can control whether a file should be considered for end-of-line conversion with the text attribute. Setting it enables end-of-line conversion, and unsetting it disables it. Setting it to the auto value makes Git guess if the given file is a text file; if it is, end-of-line conversion is enabled. For files where the text attribute is unspecified, Git uses core.autocrlf to decide whether to treat them as text=auto case.
How Git detects if a file contains binary data
To decide whether a file contains binary data, Git examines the beginning of the file for an occurrence of a zero byte (the null / NUL character or \0). When deciding whether to convert a file (as in end-of-line conversion), the criterion is stricter: for a file to be considered text, it must have no nulls, and no more than around 1% of it should be non-printable characters.
However, this means that Git usually considers files saved in the UTF-16 encoding to be binary.
To decide what line ending type Git should use in the working directory for text files, you need to set up the core.eol configuration variable. This can be set to crlf, lf, or native (the last is the default). You can also force a specific line ending for a given file with the eol=lf or eol=crlf attribute:
| Old crlf attribute | New text and eol attributes |
|---|---|
crlf | text |
- crlf | - text |
crlf=input | eol=lf |
Table 3.1 – Backward compatibility of the text and eof attributes with the crlf attribute
End-of-line conversion bears a slight chance of corrupting data. If you want Git to warn or prevent conversion for files with a mixture of LF and CRLF line endings, use the core.safecrlf configuration variable.
Sometimes, Git might not detect that a file is binary correctly, or there may be some type of file that is nominally text, but which is opaque to a human reader. Examples include PostScript documents (*.ps) and Xcode build settings (*.pbxproj). Such files should not be normalized and using textual diff for them doesn’t make sense. You can mark such files explicitly as binary with the binary attribute macro (which is equivalent to - text -diff):
*.ps binary*.pbxproj binaryWhat to do if files start without end-of-line normalization
When the normalization of line endings is turned on in the repository (by editing the .gitattributes file), you should also force the normalization of files. Otherwise, the change in newline representation will be misattributed to the next change to the file. This can be done, for example, with the git add --renormalize command. This should also be done when changing which files have the text attribute.
Diff and merge configuration
Section titled “Diff and merge configuration”In Git, you can use the attributes functionality to configure how to show differences between different versions of a file, and how to do a three-way merge of its contents. This can be used to enhance that operation, making diff more attractive and merge less likely to conflict. It can even be used to make it possible to effectively diff binary files, or to describe differences in a specific way.
In both cases, we would usually need to set up the diff and/or merge driver. The attributes file only tells us which driver to use; the rest of the information is contained in the configuration file, and this configuration is not automatically shared among developers, unlike the .gitattributes file (though you can create a shared configuration fragment, add it to the repository, and have developers include it in their local per-repository config via the relative include.path). The reason for this behavior is easy to understand – the tool’s configuration may be different on different computers, and some tools may be not available for the developer’s operating system of choice. But this means that some information needs to be distributed out-of-band.
There are, however, a few built-in diff drivers and merge drivers that anyone can use without further configuration.
Generating diffs and binary files
Section titled “Generating diffs and binary files”Diffs that are generated for particular files are affected by the diff attribute. If this attribute is unset, Git will treat files as binary concerning generating diffs and show just binary files differ (or show a binary diff). Setting it will force Git to treat a file as text, even if it contains byte sequences that normally mark the file as binary, such as the null (\ 0) character.
You can use the diff attribute to make Git more effectively describe the differences between two versions of a binary file via a diff driver. In this case, you have two options: the easier one is to tell Git how to convert a binary file into a text format, or how to extract text information (for example metadata) from the binary data. This text representation is then compared using the ordinary textual diff command. Even though conversion to text usually loses some information, the resulting differences is useful for human viewing (even though it is not information about all the changes).
This can be done with the textconv config key for a diff driver, where you specify a program that takes the name of the file as an argument and returns a text representation on its output.
For example, you might want to see the difference in the contents of Microsoft Word documents and see the difference in metadata for JPEG images. First, you need to put something like this in your .``gitattributes file:
*.doc diff=word2text*.jpg diff=exifFor example, you can use the catdoc program to extract text from binary Microsoft Word documents and exiftool to extract EXIF metadata from JPEG images.
Because conversion can be slow, Git provides a mechanism to cache the output in the form of the Boolean cachetextconv attribute; the cached data is stored using notes (this mechanism will be explained in Chapter 10, Keeping History Clean). The part of the configuration file that’s responsible for this setup looks like this:
[diff "word2text"] textconv = catdoc# cached data will be stored in refs/notes/textconv/exif[diff "exif"] textconv = exiftool cachetextconv = trueYou can see what the output of the textconv filter looks like with git show, or with git cat-file -p with the -- textconv option.
The more complicated but also more powerful option is to use an external diff driver (an attribute version of the global driver that can be specified with the GIT_EXTERNAL_DIFF environment variable or the diff.external configuration variable) with the command option of the diff driver. However, when choosing to use this option, you lose some options that Git diff gives for free: colorization, word diff, and combined diff for merges.
Such a program will be called with seven parameters: path, old-file, old-hex, old-mode, new-file, new-hex, and new-mode. Here, old-file and new-file are files that the diff driver can use to read the contents of two versions of the differing file, old-hex and new-hex are SHA-1 identifiers of file contents, and old-mode and new-mode are octal representations of file modes. The command is expected to generate a diff -like output. For example, you might want to use the XML-aware diff tool to compare XML files:
$ echo "*.xml diff=xmldiff" >>.gitattributes$ git config diff.xmldiff.command xmldiff-wrapper.shThis example assumes that you have written the xmldiff-wrapper.sh shell script to reorder options so that they fit the expectations of the XML diff tool.
Configuring diff output
Section titled “Configuring diff output”The diff format that Git uses to show changes for users was described in detail in Chapter 2, Developing with Git. Each group of changes (called a hunk) in textual diff output is preceded by the hunk header line, as shown here:
@@ -18,6 +19,8 @@ int cmd_http_fetch(int argc, const char **argv,The text after the second @@ is meant to describe the section of the file where the chunk is; for C source files, it is the start of the function. The decision on how to detect the beginning of such a section depends on the type of file. Git allows you to configure this by setting the xfuncname configuration option of the diff driver to the regular expression, which matches the description of the section of the file. For example, for LaTeX documents, you might want to use the following configuration for the tex diff driver (you don’t need to as tex is one of the pre-defined, built-in diff drivers):
[diff "tex"] xfuncname = "^(\\\\(sub)*section\\{.*)$" wordRegex = "\\\\[a-zA-Z]+|[{}]|\\\\.|[^\\{}[:space:]]+"The wordRegex configuration defines what word is to define it for the git diff --word-diff command (described in Chapter 2, Developing with Git, near the end of the Unified diff output section). Here, it’s being used for LaTeX documents.
Note
You would need to double the backslashes: \\ matches the literal backslash, \, in a regexp, so you need to use \\\\ here (which is typical for storing regexps in strings).
Performing a three-way merge
Section titled “Performing a three-way merge”You can also use the merge attribute to tell Git to use specific merge strategies for specific files or classes of files in your project. By default, Git will use the thee-way merge driver (similar to rcsmerge) for text files, and it will take our (being merged) version and mark the result as a conflicted merge for binary files. You can force a three-way merge by setting the merge attribute (or by using merge=text); you can force binary-like merging by unsetting this attribute (with -merge, which is equivalent to merge=binary).
You can also write your merge driver or configure Git to use a third-party external merge driver. For example, if you keep a GNU-style ChangeLog file in your repository (with a curated list of changes with their description), you can use the git-merge-changelog command from the G NU Portability Library (Gnulib). You need to add the following to the appropriate Git config file:
[merge "merge-changelog"] name = GNU-style ChangeLog merge driver driver = git-merge-changelog %O %A %BHere, the token, %O, in merge.merge-changelog.driver will be expanded to the name of the temporary file holding the contents of the merge ancestor’s (old) version. The %A and %B tokens expand to the names of temporary files holding contents being merged – that is, the current (ours, merged into) version and the other branches’ (theirs, merged) version, respectively. The merge driver is expected to leave the merged version in the %A file, exiting with a non-zero status if there is a merge conflict. You can also use %L to denote the conflict marker size and %P to find a pathname where the merged results will be stored.
Note
You can use a different driver for an internal merge between common ancestors (when there is more than one). You can do this by setting the merge.*.recursive configuration variable for a given driver. For example, here, you can use the predefined binary driver.
Of course, you will also need to tell Git to use this driver for ChangeLog files, adding the following line to .gitattributes:
ChangeLog merge=merge-changelogTransforming files (content filtering)
Section titled “Transforming files (content filtering)”Sometimes, the format of the content you want to put in a version control system may depend on where it is stored, be it on disk or in the repository, with different shapes in different places that are more convenient for Git, the platform (operating system), the filesystem, and the user to use. End-of-line conversion can be considered a special case for such an operation.
To do this, you need to set the filter attribute for appropriate paths and configure the clean and smudge commands of the specified filter driver (either command can be left unspecified for a pass-through filter). When checking out the file matching the given pattern, the smudge command is fed file contents from the repository in its standard input, and its standard output is used to update the file in the working directory. See Figure 3*.1* for details:

Figure 3.1 – The “smudge” filter is run on checkout (when writing files to the working directory)
Similarly, the clean command of a filter is used to convert the contents of the worktree file into a shape suitable to be stored in the repository; see Figure 3*.2*:

Figure 3.2 – The “clean” filter is run when files are staged (added to the index, also known as the staging area)
When specifying a command, you can use the %f token, which will be replaced by the name of the file the filter is working on.
One simple example of how you can use this feature is to use the rezip script for OpenDocument Format (ODF) files. ODF documents are ZIP archives of mainly XML files. Git uses compression itself and also does deltaification (but cannot do it on already compressed files); the idea is to store uncompressed files in the repository but to check out compressed files:
[filter "opendocument"] clean = "rezip -p ODF_UNCOMPRESS" smudge = "rezip -p ODF_COMPRESS"Of course, you also need to tell Git to use this filter for all kinds of ODF files:
*.odt filter=opendocument*.ods filter=opendocument*.odp filter=opendocumentAnother example of an advisory filter is to use the indent program to force a code formatting convention, as shown in the following example, or gofmt for the Go programming language. A similar example would be to replace tabs with spaces on check-in:
[filter "indent"] clean = indentYet another example is nbdev, where you can install a filter that uses the nbdev_clean command to strip metadata and cell output from Jupyter Notebook files. This is done to reduce the number of merge conflicts and to avoid storing generated data in the repository.
Obligatory file transformations
Section titled “Obligatory file transformations”Another use of content filtering is to store the content that cannot be directly used in the repository and turn it into a usable form upon checkout.
One such example might be to use .gitattributes files to configure Git so that it stores large binary files outside the Git repository (such files are often only used by a subset of developers); inside the repository, there is only an identifier that allows us to get file contents from external storage. That’s how git-media works:
$ git config filter.media.clean "git-media filter-clean"$ git config filter.media.smudge "git-media filter-smudge"$ echo "*.mov filter=media -crlf" >> .gitattributesTip
You can find the git-media tool at https://github.com/alebedev/git-media. Other similar tools will be mentioned in Chapter 12, Managing Large Repositories, as one of the possible solutions to the problem of handling large files.
Another example of obligatory transformations would be encrypting sensitive content or replacing a local sensitive program configuration that is required for an application to work (for example, a database password) with a placeholder. Because running such a filter is, like in the preceding example, required to get useful content, you can mark it as such:
[[filter "clean-password"] clean = sed -e 's/^pass = .*$/pass = @PASSWORD@/' smudge = sed -e 's/^pass = @PASSWORD@/pass = passw0rd/' requiredImportant note
This is only a simplified example; in real use, you would have to consider the security of the config file itself if you do this or store the real password in an external smudge script. In such a case, you should also set up pre-commit, pre-push, and update hooks to ensure that the password won’t make it to the public repository (see Chapter 13, Customizing and Extending Git, for details).
If many files need to be processed, and the time it takes to invoke and run the clean and smudge scripts becomes a problem, you can configure Git to use a program that will process all files with a single filter invocation for the entire lifetime of a Git command. You can define such a filter with a process key in place of clean and smudge.
Keyword expansion and substitution
Section titled “Keyword expansion and substitution”Sometimes, though rare, there is a need to have a piece of dynamic information about the versioned file in the contents of the file itself. To keep such information up to date, you can request the version control system to perform keyword expansion: replace the keyword anchor in the form of a string of text (in the file contents) formatted as $Keyword$, with the keyword inside dollar characters (keyword anchor). This is usually replaced by a version-control system with $Keyword: value$, which is a keyword followed by its expansion.
The main problem with doing this in Git is that you cannot modify the file contents stored in the repository with information about the commit after you’ve committed because of the way Git works (more information about this can be found in Chapter 10, Keeping History Clean). This means that keyword anchors must be stored in the repository as-is, and only expanded in the worktree on checkout. However, this is also an advantage; you would get no spurious differences due to keyword expansion when examining the history.
The only built-in keyword that Git supports is $Id$: its value is the SHA-1 identifier of the file contents (the SHA-1 checksum of the blob object representing the file contents, which is not the same as the SHA-1 of the file; see Chapter 10, Keeping History Clean, to learn how objects are constructed). You need to request this keyword expansion by setting the ident attribute for a file.
However, you can write your keyword expansion support with an appropriate filter while defining the smudge command, which would expand the keyword, and the clean command, which would replace the expanded keyword with its keyword anchor.
With this mechanism you can, for example, implement support for the $Date$ keyword, expanding it on checkout to the date when the file was last modified:
[filter "dater"] clean = sed -e 's/\\\$Date[^\\\$]*\\\$/\\\$Date\\\$/' smudge = expand_date %fThe expand_date script, which is passed the name of the file as an argument, could run the git log --pretty=format:"%ad" "$1" command to get the substitution value, for example.
However, you need to remember another limitation: for better performance, Git does not touch files that did not change, be it on commit, on switching the branch (on checkout), or on rewinding the branch (on reset). This means that this trick cannot support keyword expansion for the date of the last revision of a project (as opposed to the last revision that changed the file).
If you need to have such information in distributed sources (for example, the description of the current commit, or how long it was since the tagged release), you can either make it a part of the build system, or use keyword substitution for the git archive command. The latter is quite a generic feature: if the export-subst attribute is set for a file, Git will expand the $Format:<PLACEHOLDERS>$ generalized keyword when adding the file to an archive.
Limitation of the keyword expansion with export-subst
The expansion of the $Format$ meta-keyword depends on the availability of the revision identifier; it cannot be done if you, for example, pass the SHA-1 identifier of a tree object to the git archive command.
The placeholders are the same as for the --pretty=format: custom formats for git log, which are described in Chapter 4, Exploring Project History. For example, the $Format:%H$ string will be replaced (not expanded) by the commit hash. It is an irreversible keyword substitution; there is no trace of the keyword in the result of the archive (export) operation.
Other built-in attributes
Section titled “Other built-in attributes”You can also tell Git not to add certain files or directories when generating an archive. For example, in the user-facing archive, you may not want to include the directory with distribution tests, which are useful for the developer but not for end users (those tests may require additional tools or checking the quality of the program and processing it rather than checking the correctness of the application behavior). This can be done by setting the export-ignore attribute – for example, by adding the following line to the .``gitattributes file:
# Do not include extra tests in the archivext/ export-ignoreAnother thing that can be configured with file attributes is defining what diff and apply should consider a whitespace error for specific types of files; this is a fine-grained version of the core.whitespace configuration variable. Note that the list of common whitespace problems to take notice of should use commas as an element separator, without any surrounding whitespace, when put in the .gitattributes file. See the following example (taken from the Git project):
* whitespace=!indent,trail,space*.[ch] whitespace=indent,trail,space*.sh whitespace=indent,trail,spaceWith file attributes, you can also specify the character encoding that is used by a particular file by providing it as a value of the encoding attribute. Git can use it to select how to display the file in GUI tools (for example, gitk and git gui). This is a fine-grained version of the gui.encoding configuration variable and is only used when explicitly asked for due to performance considerations. For example, GNU gettext Portable Object (.po) files holding translations should use the UTF-8 encoding:
/po/*.po encoding=UTF-8To have Git convert between UTF-8 encoding in the staging area and the repository, as well as specify the encoding of a file in the working directory on checkout, you can use the working-tree-encoding attribute. For example, PowerShell script files (*.ps1) are sometimes encoded in UTF-16; files encoded using this encoding are interpreted by Git as binary. For diff and other commands to work correctly, you might want to use the following command:
*.ps1 text working-tree-encoding=UTF-16LE eol=CRLFNote
Reencoding might slow down certain Git operations.
Defining attribute macros
Section titled “Defining attribute macros”In the Identifying binary files and end-of-line conversions section, we learned how to mark binary files with the binary attribute. The binary attribute is the attribute macro, expanding to -diff -merge -text (unsetting three file attributes). It would be nice to define such macros for arbitrary combinations of attributes. There can be more than one pattern matching a given type of file, but one .gitattributes line can contain only one file pattern. If we want to have the same attributes for different types of files, attribute macros allow avoiding duplication.
Git allows us to define such macros, but only in top-level .gitattributes files, namely core.attributesFile, .git/info/attributes, or .gitattributes in the main (top-level) directory of a project. The built-in binary macro could have been defined as follows:
[attr]binary -diff -merge -textYou can also define your own attributes. In this case, you can use the git check-attr command to programmatically check which attributes are set for a given file, or what the value is of an attribute for a set of files.
Fixing mistakes with the reset command
Section titled “Fixing mistakes with the reset command”At any stage during development, you might want to undo an operation, fix mistakes, or abandon your current work. There is no git undo command in core Git, and neither is there support for the universal --undo option in Git commands, though many commands have an --abort option to abandon current work in progress (WIP). One of the reasons why there is no such command or option yet is the ambiguity on what needs to be undone (especially for multi-step operations).
Many mistakes can be fixed with the help of the git reset command. It can be used for various purposes and in various ways; understanding how this command works will help you in using it in any situation, which is not limited to the provided example usage.
Note that this section only covers the full-tree mode of git reset; the description of what git reset -- <file> does, which is an alternative to using the more modern git restore <file> command, has been left for the Managing worktree and staging area section at the end of this chapter.
Rewinding the branch head, softly
Section titled “Rewinding the branch head, softly”The git reset command in its full-tree mode affects the current branch head, and can also affect the index (the staging area) and the working directory. This reset does not change which branch is current, as opposed to git checkout or git switch.
To reset only the current branch head and not touch the index or the working tree, you can use git reset --soft [<revision>] (if a revision is not given, it defaults to HEAD):

Figure 3.3 – Before and after a soft reset
Effectively, we are just changing the pointer of the current branch (master in the example shown in Figure 3*.3*) to point to a given revision (HEAD^ – the previous commit in the example). Neither the staging area nor the working directory is affected. This leaves all your changed files (and all files that differ between the old and new revision pointed by branch) in the Changes to be committed state, as git status would put it.
Removing or amending a commit
Section titled “Removing or amending a commit”The way the command works means that a soft reset can be used to undo the act of creating a commit. This can be used to amend a commit, though it is far easier to simply use the --amend option of git commit.
Let’s take a look at the following command:
$ git commit --amend [<options>]This is equivalent to the following:
$ git reset --soft HEAD^$ git commit --reedit-message=ORIG_HEAD [<options>]The git commit --amend command also works for merge commits as opposed to using a soft reset. When amending a commit, if you want to just fix the commit message, there will be no additional options. If you want to include a fix from the working directory without changing the commit message, you can add --all --no-edit. If you want to fix the authorship information after correcting the Git configuration, use -- reset-author --no-edit.
You learned how amending a commit changes the graph of revisions in Chapter 2, Developing With Git, in the Amending a commit section.
Squashing commits with reset
Section titled “Squashing commits with reset”You are not limited to rewinding the branch head to just the previous commit. Using a soft reset, you can squash a few earlier commits (for example, commit and bugfix, or introducing new functionality and using it), making one commit out of two (or more); alternatively, you can instead use the squash instruction of interactive rebase, as described in Chapter 10, Keeping History Clean. With the latter, you can squash any series of commits, also in the middle of the history, not just the most recent ones. You can also use git merge --squash for this.
Resetting the branch head and the index
Section titled “Resetting the branch head and the index”The default mode of reset command – the so-called mixed reset (because it is between the soft and hard forms) – changes the current branch head so that it points to a given revision, and also resets the index, putting the contents of that revision into the staging area. This mode is shown in Figure 3*.4*:

Figure 3.4 – Before and after a mixed reset
This leaves all your changed files (and all files that differ between the old and new revision pointed by branch) in the Changes not staged for commit state, as git status would put it. The git reset --mixed command will also report what has not been updated using the short status format:
$ git reset HEAD^Unstaged changes after reset:M README.mdThis version of the reset command can be used, for example, to undo all additions of new files. This can be done by running git reset, if you didn’t stage any changes (or that you can put up with losing them). If you want to un-add a particular file, use git rm -- cached <file>.
Splitting a commit in two with reset
Section titled “Splitting a commit in two with reset”You can use a mixed reset to split a commit in two. First, run git reset HEAD^ to reset the branch head and the index to the previous revision. Then, interactively add changes that you want to have in the first commit, and then create this first commit from the index (git add -i and git commit). A second commit can then be created from the working directory state (git commit -a).
If it is easier to interactively remove changes, that’s also an option. Use git reset --soft HEAD^, interactively un-stage changes with an interactive per-file reset, create the first commit from the constructed state in the index, and create the second commit from the working directory.
Here, again, like for squashing commits, you can use the interactive rebase to split commits further in the history. The rebase operation will switch to the appropriate commit, at which point the actual splitting can be done, as described here.
Saving and restoring state with the WIP commit
Section titled “Saving and restoring state with the WIP commit”Suppose you are interrupted by an urgent bugfix request while you are in the middle of work on the development branch. You don’t want to lose your changes, but the worktree is a bit of a mess, and you are unable to finish the commit in time. One possible solution is to save the current state of the working area by creating a temporary commit:
$ git commit -a -m 'snapshot WIP (Work In Progress)'Then, you can handle the interruption, switching to the maintenance branch and creating a commit to fix the issue. At this point, you need to go back to the previous branch (by using checkout), remove the WIP commit from the history (using a soft reset), and go back to the un-staged starting state (with a mixed reset), as follows:
$ git switch -$ git reset --soft HEAD^$ git resetUsually, though it is much easier to just use git stash instead to handle interruptions, see the Stashing away your changes section in this chapter. On the other hand, such temporary commits can be shared with other developers, as opposed to stash (because stash stack is based on purely local data – the reflog).
Discarding changes and rewinding the branch
Section titled “Discarding changes and rewinding the branch”Sometimes, your files will get in such a mess that you want to discard all changes and return the working directory and the staging area (the index) to the last committed state to the last good version. In other cases, you might want to rewind the state of the repository to an earlier version. In such instances, a hard reset is what you need; it will change the current branch head while resetting the index and the working tree. Any changes to any tracked files will be discarded:

Figure 3.5 – Before and after a hard reset
This command can be used to undo a commit as if it had never happened, by removing it. Running git reset --hard HEAD^ will effectively discard the last commit (though it will be available for a limited time via reflog) unless this commit can be reached from some other branch.
Another common usage is to discard changes to the working directory with git reset --hard, which resets to the last committed state.
Important note
It is very important to remember that a hard reset would irrecoverably remove all changes from the staging area and working directory. You cannot undo this part of the operation! Changes are lost forever!
Moving commits to a feature branch
Section titled “Moving commits to a feature branch”Say that you were working on something on the master branch, and you have already created a sequence of commits. You have realized that the feature you are working on is more involved, and you want to continue polishing it on a separate topic branch, as described in Chapter 8, Advanced Branching Techniques. You want to move all those commits that are in master (let’s say, the last three revisions) to the aforementioned feature branch.
You need to create the feature branch, save uncommitted changes (if any), rewind the master branch while removing those topical commits from it, and switch to the feature branch to continue working (or you can use rebase instead):
$ git branch feature/topic$ git stashNo local changes to save$ git reset --hard HEAD~3HEAD is now at f82887f before$ git switch feature/topicSwitched to branch 'feature/topic'Of course, if there were local changes to save (there were none in the preceding example), this preceding series of commands would have to be followed by git stash pop.
Undoing a merge or a pull
Section titled “Undoing a merge or a pull”Hard resets can also be used to abort a failed merge. You can use git reset --hard HEAD (here, HEAD is the default value for revision and can be omitted), for example, if you decide that you don’t want to resolve the merge conflict at this time (though with modern Git you can use git merge -- abort instead).
You can also remove a successful fast-forward pull or undo a rebase (and many other operations while moving the branch head) with git reset --hard ORIG_HEAD. (Here, you can use HEAD@{1} instead of ORIG_HEAD.)
Safer reset – keeping your changes
Section titled “Safer reset – keeping your changes”A hard reset will discard your local changes, similar to how git switch --discard-changes or git checkout --force would. Sometimes, you might want to rewind the current branch while keeping the local changes: that’s what git reset --keep is for.

Figure 3.6 – Before and after a successful git reset —keep HEAD^ command
This mode resets the staging area (index entries) but retains the unstaged (local) changes that are currently in the working directory; see Figure 3*.6*. If it is not possible, the reset operation is aborted:
$ git reset --keep HEAD^error: Entry 'README' not uptodate. Cannot merge.fatal: Could not reset index file to revision 'HEAD^'.This means that local changes in the worktree are preserved and moved to the new commit, in a similar way to how git checkout <branch> works with uncommitted changes. The successful case is a bit like stashing changes away, hard resetting, and then unstashing (but with a single atomic command).
How does safe reset work?
The way git reset --keep <revision> works is by updating the version (in the working directory) of only those files that are different between the revision we rewind to and HEAD. The reset is aborted if there is any file that is different between HEAD and <revision> (and thus would need to be updated) and has local uncommitted changes.
Rebasing current changes to an earlier revision
Section titled “Rebasing current changes to an earlier revision”Suppose that you are working on something but you realize that what you have in your working directory should be in another branch, unrelated to a previous commit. For example, you might have started to work on a bug while on the master branch, and only then realized that it also affects the maintenance branch, maint.
This means that the fix should be put earlier in a branch, starting from the common ancestor of those branches (or a place where the bug was introduced). This would make it possible to merge the same fix both into master and maint, as described in Chapter 15, Git Best Practices:
$ edit$ git checkout -b bugfix-127$ git reset --keep startAn alternate solution would be to simply use git stash to move changes:
$ edit$ git stash$ git switch -c bugfix-127 start$ git stash popStashing away your changes
Section titled “Stashing away your changes”Often, when you’ve been working on a project, and things are in a messy state not suitable for a permanent commit, you want to temporarily save the current state and go to work on something else. The answer to this problem is the git stash command.
Stashing takes the dirty state of your working area – that is, your modified tracked files in your worktree and the state of the staging area – saves this state, and resets both the working directory and the index to the last committed version (to match the HEAD commit), effectively running git reset --hard HEAD. You can then reapply the stashed changes at any time.
You can also stash untracked files with the -- include-untracked option.
Stashes are saved on a stack: by default, you apply the last stashed changes (stash@{0}), though you can list stashed changes (with git stash list) and explicitly select any of the stashes.
Using git stash
Section titled “Using git stash”If you don’t expect the interruption to last long, you can simply stash away your changes, handle the interruption, and then unstash them:
$ git stash$ # ... handle interruption ...$ git stash popBy default, git stash pop will apply the last stashed changes and delete the stash if applied successfully. To see what stashes you have stored, you can use git stash list:
$ git stash liststash@{0}: WIP on master: 049d078 atoi() is deprecatedstash@{1}: WIP on master: c264051 Add error checkingYou can use any of the older stashes by specifying the stash name as an argument, or simply its number. For example, you can run git stash apply stash@{1} or git stash apply 1 to apply it, and you can drop it (remove it from the list of stashes) with git stash drop stash@{1} or git stash drop 1; the git stash pop command is just a shortcut for apply + drop.
The default description that Git gives to stashed changes (namely WIP on <branch>) is useful for remembering where you were when stashing the changes (it specifies the branch and commit) but doesn’t help you remember what you were working on, and what has been stashed away. However, you can examine the changes that were recorded in the stash as a diff with git stash show -p. But if you expect that the interruption might be more involved, you should save the current state to a stash while describing what you were working on:
$ git stash push -m 'Add <count>'Saved working directory and index state On master: Add <count>HEAD is now at 049d078 atoi() is deprecatedGit would then use the provided message to describe stashed changes when listing stashes:
$ git stash liststash@{0}: On master: Add <count>stash@{1}: WIP on master: c264051 Add error checkingSometimes, the branch you were working on when you ran git stash save has changed enough that git stash pop fails because there are too many new revisions past the commit you were on when stashing the changes. If you want to create a regular commit out of the stashed changes, or just test stashed changes, you can use git stash branch <branch name>. This will create a new branch at the revision you were at when saving the changes, switch to this branch, reapply your work there, and drop stashed changes.
Stash and the staging area
Section titled “Stash and the staging area”By default, stashing resets both the working directory and the staging area to the HEAD version. You can make git stash keep the state of the index and reset the working area to the staged state with the -- keep-index option:

Figure 3.7 – The difference between git stash with and without —keep-index
This is very useful if you used the staging area to untangle changes in the working directory, as described in the Selective commit section in Chapter 2, Developing with Git, or if you want to split the commit in two, as described in the Splitting a commit with reset section in this chapter. In both cases, you would want to test each change before committing.
The workflow would look like this:
$ git add --interactive$ git stash --keep-index$ make test$ git commit -m 'First part'$ git stash popYou can also use git stash --patch to select how the working area should look after stashing away the changes.
When restoring stashed changes, Git will ordinarily try to apply only saved worktree changes, adding them to the current state of the working directory (which must match the staging area). If there are conflicts while applying the state, they are stored in the index as usual – Git won’t drop the stash if there are conflicts.
You can also try to restore the saved state of the staging area with the --index option; this will fail if there are conflicts when you’re applying working tree changes (because there is no place to store conflicts since the staging area is busy).
Stash internals
Section titled “Stash internals”Perhaps you applied stashed changes, did some work, and then for some reason want to un-apply those changes that originally came from the stash. Maybe you mistakenly dropped the stash or cleared all stashes (which you can do with git stash clear) and would like to recover them. Or perhaps you want to see how the file looked when you stashed away changes. To do any of this, you will need to know what Git does when creating a stash entry.
To stash away your changes, Git creates two automatic commits: one for the index (staging area) and one for the working directory. With git stash --include-untracked, Git creates an additional third automatic commit for untracked files.
The commit containing the work in progress (WIP) in the working directory (the state of files tracked from there) has the commit with the contents of the staging area (the index) as its second parent. This WIP containing commit is stored in a special ref: refs/stash. Both the WIP (stash) and index commits have the revision you were on when saving changes as their first parent.
We can see this by running git log --graph or gitk --all:
$ git stash save --quiet 'Add <count>'$ git show-ref --abbrev765b095 refs/heads/master81ef667 refs/stash$ gitk --allThis can be seen in the following figure:

Figure 3.8 – The structure of the stash without and with untracked file information. Graphs were generated with gitk —all on a newly created repository with a single commit and a stash
We had to use git show-ref here (we could have used git for-each-ref instead) because git branch -a only shows branches, not arbitrary refs.
When saving untracked changes, with git stash --include-untracked, the situation is similar. Figure 3*.8* shows that the untracked file commit is the third parent of the WIP commit and that it doesn’t have any parents. It only consists of untracked files, which you can check with git ls-tree - r stash@{<n>}^3.
Well, that’s how stashing works, but how does Git maintain the stack of stashes? You may have noticed that the git stash list output and the stash@{<n>} notation therein looks like reflog; Git finds older stashes in the reflog for the refs/stash reference:
$ git reflog stash --no-decorate81ef667 stash@{0}: On master: Add <count>bb76632 stash@{1}: WIP on master: Added .gitignoreThis is why you cannot share the stack of stashes: reflogs are local to the repository and are not and cannot be synchronized when pushing or fetching.
Un-applying a stash
Section titled “Un-applying a stash”Let’s take the first example from the beginning of this section: un-applying changes from the earlier git stash apply. One possible solution to achieve the required effect is to retrieve the patch associated with working directory changes from a stash, and apply it in reverse:
$ git stash show -p stash@{0} | git apply -R -Note the -p option that was applied to the git stash show command – it forces patch output instead of a summary of changes. We could use git show -m stash@{0} (the -m option is necessary because a WIP commit representing the stash is a merge commit), or even simply git diff stash@{0}^-1, in place of git stash show -p.
Recovering stashes that were dropped erroneously
Section titled “Recovering stashes that were dropped erroneously”Let’s try the second example: recovering stashes that were accidentally dropped or cleared. If they are still in your repository and were not removed during the repository maintenance phase, you can search all commit objects that are unreachable from other refs and look like stashes (that is, they are merged commits and have a commit message using a strict pattern).
A simplified solution might look like this:
$ git fsck --unreachable |grep "unreachable commit " | cut -d" " -f3 |git log --stdin --merges --no-walk --grep="WIP on "The first line of this pipeline finds all unreachable (lost) objects, the second one filters out everything but commits and extracts their SHA-1 identifiers, and the third line filters out even more, showing only merge commits with a commit message containing the "WIP on " string.
This solution would not, however, find stashes with a custom message (those created with git stash save "message"); you would need to add another --grep.
Managing worktrees and the staging area
Section titled “Managing worktrees and the staging area”In Chapter 2, Developing with Git, we learned that, besides the working directory (worktree) where you work on changes and the local repository where you store committed changes as revisions, there is also a third section between them: the staging area, sometimes called the index.
In the same chapter, we learned how to examine the status of the working directory, as well as how to view the differences. We saw how to create a new commit out of the working directory or out of the staging area.
Now, it is time to learn how to examine and modify the state of individual files.
Examining files and directories
Section titled “Examining files and directories”It is easy to examine the contents of the working directory: you can just use the standard tools for viewing files (for example, an editor or pager) and examining directories (for example, a file manager or the dir command). But how do we view the staged contents of a file or the last committed version?
One possible solution is to use the git show command with the appropriate selector. Chapter 4, Exploring Project History, will introduce and explain the <revision>:<pathname> syntax to examine the contents of a file at a given revision. A similar syntax can be used to retrieve the staged contents, namely :<pathname> (or :<stage>:<pathname> if there is a merge conflict involving the given file; :<pathname> in itself is equivalent to :0:<pathname>).
Let’s assume that we are in the src/ subdirectory and want to see the contents of the rand.c file there as it’s in the working directory, in the staging area (using the absolute and relative path), and in the last commit (also using the absolute and the relative path):
src $ less -FRX rand.csrc $ git show :src/rand.csrc $ git show :./rand.csrc $ git show HEAD:src/rand.csrc $ git show HEAD:./rand.cTo see the list of files that are staged in the index, there is the git ls-files command. By default, it operates on the staging area contents, but it can also be used to examine the working directory. The latter feature can, as we have seen in this chapter, be used to list ignored files. This command lists all files in the specified directory. Alternatively, in the current directory, you can use :/ to denote the top-level directory of a project. The recursive behavior is caused by the fact that the index is a flat list of files, similar to MANIFEST files.
Without using the --full-name option, it would show filenames relative to the current directory (or the one specified as a parameter). In all examples, it is assumed that we are in the src/ subdirectory, as seen in the command prompt:
src $ git ls-filesrand.csrc $ git ls-files --full-name :/COPYRIGHTMakefileREADMEsrc/rand.cWhat about committed changes? How can we examine which files were in a given revision? This is where git ls-tree comes to the rescue (note that it is a plumbing command and does not default to the HEAD revision):
src $ git ls-tree --name-only HEADrand.csrc $ git ls-tree --abbrev --full-tree -r -t HEAD100644 blob 862aafd COPYRIGHT100644 blob 25c3d1b Makefile100644 blob bdf2c76 README040000 tree 7e44d2e src100644 blob b2c087f src/rand.cNote that git ls-tree is not recursive by default; you need to use the - r option.
Searching file contents
Section titled “Searching file contents”Let’s assume that you were reviewing code in the project and noticed an erroneous doubled semicolon, ;;, in the C source code. Or perhaps you were editing the file and noticed a bug nearby. You fixed it, but you’re wondering, “ How many of those mistakes are there?” You would like to create a commit to fix such errors.
Or perhaps you want to search the version that was scheduled for the next commit – that is the contents of the staging area. Perhaps you want to examine how it looks in the next branch.
With Git, you can use the git grep command:
$ git grep -e ';;'By default, this command will search tracked files in the working directory, from the current directory downwards, recursively. Note that when running the example command, we will get many false positives from shell scripts, for example. So, let’s limit the search space to only C source files:
$ git grep -e ';;' -- '*.c'The quotes around *.c are necessary for Git to do the glob pattern expansion (path limiting) instead of git grep getting the list of files expanded by the shell. We still have many false matches from the forever loop C idiom:
for (;;) {With git grep, you can construct complex conditions, excluding false positives. Say that we want to search the whole project, not only the current directory, and avoid false positives:
$ git grep -e ';;' --and --not 'for *(.*;;' -- '**/*.c'To search the staging area, use git grep --cached or the equivalent – and perhaps easier to remember – git grep --staged. To search the next branch, use git grep next --; this construction can be used to search any version.
Un-tracking, un-staging, and un-modifying files
Section titled “Un-tracking, un-staging, and un-modifying files”If you want to undo some file-level operation (if, for example, you have changed your mind about tracking files or staging changes), then look no further than git status hints (add --ignored to get advice about ignored files):
$ git status --ignoredOn branch masterChanges to be committed: (use "git restore --staged <file>..." to unstage)Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory)Untracked files: (use "git add <file>..." to include in what will be committed)Ignored files: (use "git add -f <file>..." to include in what will be committed)You need to remember that only the contents of the working directory and the staging area can be changed. Committed changes are immutable (though you can rewind the history or replace it).
If you want to undo adding a previously untracked file to the index – or remove a formerly tracked file from the staging area so that it will be deleted (not present) in the next commit while keeping it in the working directory – use git rm -- cached <file>.
The difference between the —cached (—staged) and —index options
Many Git commands, including git diff, git grep, and git rm, support the --cached option (or its alias, --staged). Others, such as git stash, have the --index option (the index is an alternate name for the staging area). These are not synonyms (as we will later see with git apply command, which supports both).
The --cached option is used to ask the command that usually works on files in the working directory to only work on the staged contents instead. For example, git grep --cached will search the staging area instead of the working directory, and git rm --cached will only remove a file from the index, leaving it in the worktree.
The --index option is used to ask the command that usually works on files in the working directory to also affect the index, additionally. For example, git stash apply --index not only restores stashed working directory changes but also restores the index.
If you asked Git to record the state of some file in the staging area but changed your mind, you can reset the staged contents of the file to the committed version with git restore --staged <file> (--source=HEAD is the default) or git reset HEAD -- < file>.
If you edited a file incorrectly to the point that the working directory version is a mess and you want to restore it to the version from the index, use git restore <file> (--worktree is the default if --staged is not given) or git checkout -- <file>. If you staged some of this mess and would like to reset both the worktree and the staging area to the last committed version, use git restore --worktree --staged <file> or git checkout HEAD -- < file> instead.
Important note
These commands do not undo operations; they restore the previous state based on a backup that is the worktree, the index, or the committed version. For example, if you staged some changes, modified a file, and then added modifications to the staging area, you can reset the index to the committed version, but not to the state after the first and before the second git add.
Resetting a file to the old version
Section titled “Resetting a file to the old version”You can use any revision when restoring a file, with a per-file reset and per-file checkout. For example, to replace the current worktree version of the src/rand.c file with the one from the previous commit, you can use git restore -s HEAD^ src/rand.c or git checkout HEAD^ -- src/rand.c (or redirect the output of git show HEAD^:src/rand.c to a file). To put the version from the next branch into the staging area, run git restore -s next src/rand.c or git reset next -- src/rand.c.
Note that git add <file>, git restore <file>, git reset <file >, and git checkout <file> all enter interactive mode for a given file when invoked with the --patch option. This can be used to hand-craft a staged or worktree version of a file by selecting which changes should be applied (or un-applied).
Tip
When using Git from the command line, you might need to put a double dash, --, after other options and before the filename if, for example, you have a file with the same name as a branch.
Cleaning the working area
Section titled “Cleaning the working area”Untracked files and directories may pile up in your working directory. They can be leftovers from merges or be temporary files, proof of concept work, or perhaps mistakenly put there. Whatever the case, often, there is no pattern to them, and you don’t need and don’t want to make Git ignore them (see the Ignoring files section of this chapter); you just want to remove them. You can use the git clean command for that.
Because untracked files do not have a backup in the repository, and you cannot undo their removal (unless the operating system or the filesystem supports undo or trashcan), it’s advisable to first check which files can be removed with --dry-run / -n. By default, actual removal requires the -- force / -f option:
$ git clean --dry-runWould remove patch-1.diffGit will clean all untracked files recursively, starting from the current directory. You can select which paths are affected by listing them as an argument; you can also exclude additional types of files with the --exclude=<pattern> option. You can also interactively select which untracked files to delete with the -- interactive option:
$ git clean --interactiveWould remove the following items: src/rand.c~ screenlog.0*** Commands *** 1: clean 2: filter by pattern 3: select by numbers 4: ask each 5: quit 6: helpWhat now>The clean command also allows us to only remove ignored files, for example, to remove build products but keep manually tracked files, with the -X option. However, usually, it is better to leave removing build byproducts to the build system, so that the project files can be cleaned without having to clone the repository.
You can also use git clean -x in conjunction with git reset --hard to create a pristine working directory to test a clean build by removing both ignored and not-ignored untracked files and resetting tracked files to the committed version.
Multiple working directories
Section titled “Multiple working directories”For a long time, Git allowed you to specify where to find the administrative area of the repository (the .git directory). This can be done by appending the --git-dir=<path> option to the git command (that is, the git --git-dir=<path> <command> construct), or by setting the GIT_DIR environment variable. This feature makes it possible to work from the detached working directory.
With modern Git, you have a better solution to creating a new linked work tree than manual configuration: git worktree add <path> <branch>. This feature allows us to have more than one branch checked out. For convenience, if you omit the <branch> argument, then the new branch will be created based on the name of the created worktree.
This mechanism can be used instead of git stash if you need to switch to a different branch, but your current working directory, and possibly also the staging area, is in a state of high disarray. Instead of disturbing it, you can create a temporary linked working tree to make a fix and remove it when you’re done. For example, you might need to do this to urgently fix a security bug in a separate branch.
Each detached worktree should be associated with and have checked out different branches or be on the anonymous branch (detached HEAD) to avoid problems. You can override this safety with the -- force option.
You can remove any detached worktree with git worktree remove or by removing its directory and allowing it to be pruned. If a working tree is on a portable device or network disk, which may not always be available, we can lock the worktree so that it can’t be pruned (and unlock if it is no longer needed).
To examine details about each working directory, such as the currently checked-out branch, and see if it is locked, you can use the git worktree list command.
Summary
Section titled “Summary”In this chapter, we learned how to better manage the contents of the working directory and the staging area in preparation for creating a new commit.
We now know how to undo the last commit, how to drop changes to the working area, how to retroactively change the branch we are working on, and other uses of the git reset command. We also understand the three (and a half) forms of reset.
We also learned how to examine and search the contents of the working directory, the staging area, and committed changes. We now know how to use Git to copy the file version from the worktree, the index, or the HEAD commit into the worktree or the index. We can use Git to clean (remove) untracked files.
This chapter explained how to configure how files are handled in the working directory and how to make Git ignore files (by making them intentionally untracked) and why. It described how to handle the differences between line-ending formats between operating systems. It also explained how to enable (and write) keyword expansion, how to configure how binary files are handled, and how to enhance diff and merge specific classes of files.
Finally, we learned to stash away changes to handle interruptions and to make it possible to test interactively prepared commits, before creating a commit. This chapter explained how Git manages stashes, enabling us to go beyond built-in operations.
This chapter, together with Chapter 2, Developing with Git, taught you how to contribute to a project.
The following chapters will teach you how to collaborate with other people, how to send what you contributed, and how to merge changes from other developers. We will start with two chapters explaining how to explore ad search project history with Chapter 4*, Exploring Project History* and Chapter 5*, Searching Through* the Repository.
Questions
Section titled “Questions”Answer the following questions to test your knowledge of this chapter:
- How can you avoid having a large number of build artifacts appear in the
gitstatusoutput? - Let’s assume that you use a custom domain-specific language (DSL) or a programming language without built-in support in Git, such as Julia. How can you configure Git so that it provides better support for this language?
- How can you squash the two most recent commits while making one commit out of them?
- How can you split the most recent commit into two commits?
- What should you do if an urgent change is needed (for example, because of a security bug) but the working area is in a messy state and you don’t want to lose your work?
- How can you search through an old revision of the project – for example, a version tagged
v0.1– without checking out that revision?
Answers
Section titled “Answers”Here are the answers to the questions given above:
- Add patterns matching the pathnames of those build artifacts to a
.``gitignorefile. - Define a custom
diffdriver and provide the regular expression pattern matching the main “sections” of code withxfuncname. Also, add an appropriate regular expression defining words in that programming language withwordRegex, and perhaps also define whitespace problems with thewhitespaceattribute. - Use
git reset --soft HEAD~2to rewind the branch and create a joined commit withgit commit, or use interactive rebase. - Perform a soft reset,
git reset --soft HEAD^, construct the first commit withinteractive add, test the code withgit stash --keep-index, pop the stash if the tests pass, and create the first commit withgit commitand the second withgit commit -a; there are other solutions. - Use
git stashto stash away current changes, create a WIP commit, or create a new detached working area for the urgent work withgitworktree add. - To search file contents from a revision tagged as v0.1, you can use
git grep -e <pattern> v0.1.
Further reading
Section titled “Further reading”To learn more about the topics that were covered in this chapter, take a look at the following resources:
- Scott Chacon and Ben Straub, Pro Git, 2.2 Git Basics – Recording Changes to the Repository, the Ignoring files section: https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository#_ignoring
- Scott Chacon and Ben Straub, Pro Git, 7.3 Git Tools – Stashing and Cleaning: https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning
- Scott Chacon and Ben Straub, Pro Git, 8.2 Customizing Git – Git Attributes: https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes
- gitattributes manpage - Defining attributes per path: https://www.git-scm.com/docs/gitattributes
- gitignore manpage - Specifies intentionally untracked files to ignore: https://www.git-scm.com/docs/gitignore
- Pragati Verma, A Guide to Git Stash (2021): https://dev.to/pragativerma18/a-guide-to-git-stash-2h5d
- Andrew Knight, Ignoring Files with Git (2018): https://automationpanda.com/2018/09/19/ignoring-files-with-git/
- Dragos Barosan, New in Git: switch and restore (2021): https://www.banterly.net/2021/07/31/new-in-git-switch-and-restore/