Skip to content
ImagineWorld

Managing Large Repositories

node_idnode-book_mastering-git_chapter-12-managing-large-repositories
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleManaging Large Repositories
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Managing Large Repositories

Section titled “Chapter 12 — Managing Large Repositories”

Because of its distributed nature, Git includes the full change history in each copy of the repository. Every clone gets not only all the files but every revision of every file ever committed. This allows for efficient development (local operations not involving a network are usually fast enough so that they are not a bottleneck) and efficient collaboration with others (their distributed nature allows for many collaborative workflows).

But what happens when the repository you want to work on is huge? Can we avoid taking a large amount of disk space for version control storage? Is it possible to reduce the amount of data that end users need to retrieve while cloning the repository? Do we need to have all files present to be able to work on a project?

If you think about it, there are broadly three main reasons for repositories to become massive: they can accumulate a very long history (every revision direction), they can include huge binary assets that need to be managed together with code, the project can include a large number of files (every file direction), or any combination of those. For those scenarios, the techniques and workarounds are different and can be applied independently, though modern Git also includes a one-stop solution.

Submodules (presented in the previous chapter, Managing Subprojects) are sometimes used to manage large-size assets. This chapter will describe how this can be done while also presenting alternate solutions to the problem of handling large binary files and other large assets in Git.

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 clone
  • Faster operations with filesystem monitor

The simplest way to configure Git so that it works better with large repositories, apart from enabling the relevant Git features, is to use the built-in scalar tool. This executable has been present in Git since version 2.38, which was released in 2022. Earlier, it was a separate project, then part of Microsoft’s fork of Git.

Using it is very simple: instead of using git clone, you use scalar clone. If the repository has already been cloned, you can run scalar register to achieve the same result. One of the things that the command does is schedule background maintenance; you can stop this and remove the repository from the list of repositories that have been registered with scalar by using the scalar unregister command. The scalar delete command unregisters the repository and removes it from the filesystem.

After a scalar upgrade (which might be caused by moving to newer Git), you can run scalar reconfigure --all to upgrade all repositories registered with Scalar.

By registering the repository with Scalar (or the top-level directory of the project, which is called the enlistment in the Scalar documentation), you can turn on partial clone and sparse-checkout, configure Git to use filesystem monitor, and turn on background maintenance tasks such as repository prefetching.

All these features will be described in the following sections, as will some other features for handling large Git repositories that are more specific to users’ needs.

Handling repositories with a very long history

Section titled “Handling repositories with a very long history”

Even though Git can effectively handle repositories with a long history, very old projects spanning a huge number of revisions can become a pain to clone. In many cases, you aren’t interested in ancient history and don’t want to pay the time to get all the revisions of a project and the disk space to store them. In this section, we will talk about techniques that you can use to clone truncated history, or how to make Git fast despite the long history.

For example, if you want to propose a new feature or a bug fix, you might not want to wait for the full clone to finish, which may take a while.

Editing project files online

Some Git repository hosting services, such as GitHub, offer a web-based interface to manage repositories, including in-browser file management and editing. They may even automatically create a fork of the repository so that you can write and propose changes.

But a web-based interface doesn’t cover everything, and you might be using self-hosted repositories or a service that doesn’t provide this feature.

However, fixing the bug might require running git bisect on your machine, where the regression bug is easily reproducible (see Chapter 4, Exploring Project History, for how to use bisection). If you’re tight on space and time, you might want to try to do either a shallow clone (described in the following subsection) or a sparse clone (described later in this chapter).

Using shallow clones to get truncated history

Section titled “Using shallow clones to get truncated history”

The simple solution to a fast clone and to save disk space is to perform a shallow clone using Git. This operation allows you to get a local copy of the repository with the history truncated to a particular specified depth – that is, the number of latest revisions.

How do you do it? Just use the -- depth option:

$ git clone --depth=1 https://git.company.com/project

The preceding command only clones the most recent revision of the primary branch. This trick can save quite a bit of time and relieve a great deal of load from the servers. Often, a shallow clone finishes in seconds rather than minutes, which is a significant improvement. This can be useful if you’re only interested in checking out project files, and not in the whole history, such as what’s inside Git hooks or GitHub Actions – that is, the case of builds where you delete the clone immediately after the action.

Since version 1.9, Git supports pull and push operations even with shallow clones, though some care is still required. You can change the depth of a shallow clone by providing the --depth=<n> option to git fetch (however, note that tags for the deepened commits aren’t fetched). To turn a shallow repository into a complete one, use --unshallow.

Important note

Since the commit history in a shallow clone is truncated, commands such as git merge-base and git log show different results than they would in a full clone. This will happen if you try to go outside the depth of the clone. Also, because of how the Git server is optimized, incremental fetch in a shallow repository might take longer than using fetch in a full repository. Fetch might also unexpectedly make the repository not so shallow.

Note that git clone --depth=1 may still get all the branches and all the tags. This can happen if the remote repository doesn’t have HEAD, so it doesn’t have a primary branch selected; otherwise, only the tip of the said single branch is fetched. Long-lived projects usually had many releases during their long history. To save time, you would need to combine shallow clone with the next solution: branch limiting.

With modern Git, it might make more sense to use the partial clone feature instead.

By default, Git clones all the branches and tags (if you want to fetch notes or replacements, you need to specify them explicitly). You can limit the amount of history you clone by specifying that you want to clone only a single branch:

$ git clone --branch master --single-branch \
https://git.company.com/project

Because most of the project history (most of the DAG of revisions) is shared among branches, with very few exceptions, you probably won’t see a huge difference using this technique.

This feature might be quite useful if you don’t want detached orphan branches or the opposite: you only want an orphan branch (for example, with a web page for a project, or a branch used for GitHub Pages). Single-branch cloning works well in regard to saving disk space when they’re used together with a very shallow clone (with so short a history that most branches don’t have time to converge).

Making operations faster in repositories with a long history

Section titled “Making operations faster in repositories with a long history”

One of the features that makes Git faster on repositories with a very long history is the commit-graph file. Using this feature, which is turned on by default as of Git 2.24, configures Git to periodically write or update a helper file with a serialized (and easy-to-access) graph of revisions. This makes Git operations that query project history much faster.

You can turn this feature off by setting the core.commitGraph configuration variable to false. If you need to refresh the helper file, you can do this with the git commit-graph write command.

Avoiding doing the work

One unexpected place that might get slower with long history is running git status. This is caused by the command in question computing detailed ahead/behind counts for the current branch (how many commits you have on the local branch ahead of the upstream branch in the remote repository, how many commits in the remote repository you are behind).

You can turn off computing this information with the --no-ahead-behind option, or by setting the status.aheadBehind configuration variable to false. Nowadays, git status will print this advice when it is slowed by ahead/behind calculations.

Handling repositories with large binary files

Section titled “Handling repositories with large binary files”

In some specific circumstances, you might need to track huge binary assets in the code base. For example, gaming teams have to handle huge 3D models, and web development teams might need to track raw image assets or Photoshop documents. Both gaming development and web development might require video files to be under version control. Additionally, sometimes, you might want the convenience of including large binary deliverables that are difficult or expensive to generate – for example, storing a snapshot of a virtual machine image.

There are some tweaks you can make to improve how binary assets are handled by Git. For binary files that change significantly from version to version (and not just change some metadata headers), you might want to turn off the delta compression by adding -delta explicitly for specific types of files in a .gitattributes file (see Chapter 3, Managing Your Worktrees, and Chapter 13, Customizing and Extending Git). Git will automatically turn off delta compression for any file above the core.bigFileThreshold size, which is 512 MiB by default. You may also want to turn the compression off (for example, if a file is in the compressed format already). However, because core.compression and core.looseCompression are global for the whole repository, it makes more sense if binary assets are in a separate repository (submodule).

Splitting the binary asset folder into a separate submodule

Section titled “Splitting the binary asset folder into a separate submodule”

One possible way of handling large binary asset folders is to split them into a separate repository and pull the assets into your main project as a submodule. The use of submodules gives you a way to control when assets are updated. Moreover, if a developer doesn’t need those binary assets to work, they can simply exclude the submodule with assets from fetching.

The limitation is that you need to have a separate folder with these huge binary assets that you want to handle this way. Additionally, the service hosting the submodule repository with those large assets needs to be able to store those large files; many Git hosting sites impose hard limits on the maximum size of a file, or of the repository.

Storing large binary files outside the repository

Section titled “Storing large binary files outside the repository”

Another solution is to use one of the many third-party tools that try to solve the problem of handling large binary files in Git repositories. Many of them use a similar paradigm, namely storing the contents of huge binary files outside the repository while providing some kind of pointers to the contents in the checkout.

There are three parts to each such implementation:

  • How they store the information about the contents of the managed files inside the repository
  • How they share large binary files between a team
  • How they integrate with Git (and their performance penalty)

While choosing a solution, you need to take this data into account, along with the operating system support, ease of use, and the size of the community.

What’s stored in the repository and what’s checked in might be a symlink to the file or the key, or it might be a pointer file (often plain text), which acts as a reference to the actual file contents (by name or by the cryptographic hash of file contents). The tracked files need to be stored in some kind of backend for collaboration (cloud service, rsync, shared directory, and so on). Backends might be accessed directly by the client, or there might be a separate server with a defined API into which the blobs are written, which would, in turn, offload the storage elsewhere.

The tool might either require the use of separate commands for checking out and committing large files and for fetching from and pushing to the backend, or it might be integrated into Git. The integrated solution uses the clean / smudge filters to handle check-out and check-in transparently, and the pre-push hook to send large file contents transparently together. You only need to state which files to track and, of course, initialize the repository for the tool use.

The advantage of a filter-based approach is its ease of use; however, there is a performance penalty because of how this approach works. Using separate commands to handle large binary assets makes the learning curve a bit steeper but provides better performance. Some tools provide both interfaces.

Among different solutions, there’s git-annex, which has a large community and support for various backends, and Git-Large File Storage (Git-LFS), created by GitHub, which provides good Microsoft Windows support, a client-server approach, and transparency (with support for a filter-based approach). The Git-LFS extension is supported not only by GitHub but also by other Git hosting sites and software forges, such as GitLab, Bitbucket, and Gitea. Specialized services and projects for implementing Git-LFS also exist.

There are many other such tools, but those two are the most popular, and both are still maintained.

Versioning data files for data analysis and machine learning

Machine learning projects often process large files or large numbers of files. Those include the raw dataset, but also the results of various pre-processing steps, as well as the trained model.

You want to store those large files or directories somewhere to avoid having to re-download or re-compute them. On the other hand, you also want to be able to recreate everything from scratch, to make the science reproducible. Those requirements are different enough from the ones that are encountered in typical software projects that need to handle large assets, where specialized solutions for integrating data handling and version control are necessary. Among such solutions, there’s Data Version Control (DVC) and Pachyderm.

Handling repositories with a large number of files

Section titled “Handling repositories with a large number of files”

The rise in the use of monorepos (this concept was explained in detail in Chapter 11*, Managing Subprojects*) has led to the need to handle repositories with large amounts of files. In a monorepo – that is, a repository composed of many interconnected subprojects – you would usually work on a single subproject and access and change files only within a specific subdirectory.

Limiting the number of working directory files with sparse checkout

Section titled “Limiting the number of working directory files with sparse checkout”

Git includes the sparse checkout technique, which allows you to explicitly detail which files and folders you want to populate on checkout. This mode can be turned on by setting the core.sparseCheckout configuration variable to true and uses the .git/info/sparse-checkout file with the gitignore-like syntax to specify what is to appear in the working directory. The index (also known as the staging area) is populated in full, with the skip-worktree flag set for files missing from checkout.

While it can be helpful if you have a huge tree of folders, it doesn’t affect the overall size of the local repository itself. To reduce the size of the repository, it needs to be used together with sparse clone (which will be described later).

However, sparse checkout definitions are extremely generic. This makes the feature very flexible but at the cost of bad performance for large definitions and large amounts of files. With a monorepo, you don’t need that flexibility as each subproject is contained in its own subdirectory – you only directory matches in sparse checkout definitions.

To achieve this, you need to use “cone mode” sparse-checkout. Note that since Git 2.37, the non-cone mode of the sparse-checkout feature is deprecated (see, for example, the git sparse-checkout command’s documentation). This mode has the additional advantage that it is much easier to use. Everything is managed with the help of the git sparse-checkout command.

To restrict your working directory to a given set of directories, run the following command:

$ git sparse-checkout set <directory_1> <directory_2>

Earlier versions of the feature required you to run git sparse-checkout init --cone first, but using this command is no longer needed, and the init subcommand is itself being deprecated.

Tip

If you’re cloning a repository with a large number of files, you can avoid filling out the working directory with them by using the --no-checkout or --sparse option of git clone (the second option will only check out files in the top directory of the project). You can add the --filter=blob:none option for even more speed (turning on blobless sparse clone).

At any point, you can check which directories are included in your sparse-checkout definitions, and are present in your working directory, using the following command:

$ git sparse-checkout list

You can add a new directory to your existing sparse checkout with the add subcommand, as shown in the following example:

$ git sparse-checkout add <new_directory>

At the time of writing, there’s no remove subcommand. To remove a directory from the list of checked-out files, you would need to edit the contents of the .git/info/sparse-checkout file and then run the following subcommand:

$ git sparse-checkout reapply

This subcommand reapplies the existing sparse directory specifications to make the working directory match. It can also be used when some operation updates the working directory without fully respecting sparse-checkout definitions. This might be caused by using tools external to Git, or by running Git commands that do not fully support sparse checkouts.

You can turn off this feature and restore the working directory so that it includes all files by running the git sparse-checkout disable command.

Reducing the local repository size with sparse clone

Section titled “Reducing the local repository size with sparse clone”

The initial section of Chapter 11, Managing Subprojects, described how Git stores the history of the project, which includes a description of changes, directory structure, and file contents at each revision. This data is stored using different types of objects: tag objects, commit objects, tree objects, and blob objects. Objects reference other objects: tags point to commits, commits point to a parent commit(s), trees represent the state of the project at a given revision, and trees point to other trees and blobs.

When running the ordinary git clone command, the client asks the server for the latest commits (representing the latest revisions). The server provides those objects, all objects they point to, all objects those objects point to, and so on. In short, the server provides those commit objects and every other reachable object (excluding possibly those objects that the client already has). The result is that you have the whole history of the whole project available locally.

Nowadays, however, many developers have network connections available as they work. Modern Git only allows you to download a subset of objects via partial clone. In this case, Git remembers where it can get the rest of the objects, and later asks the server for more data when it turns out to be necessary.

Git’s partial clone feature can be enabled by specifying the --filter option when running the git clone command. There are several filters available, but the server that hosts the repository you’re cloning can choose to deny your filter and revert to creating a full clone.

Running git fetch in sparse clone preserves sparse clone filters, and it doesn’t download those types of objects that would not be downloaded by the initial clone.

The two most commonly used filters that should be supported by most Git hosting sites are as follows:

  • Blobless clone: git clone -- filter=blob:none <url>
  • Treeless clone: git clone -- filter=tree:0 <url>

When using the --filter=blob:none option, the initial git clone command will download everything but the blob objects (which ordinarily contain different versions of file contents for different files). The checkout part of the clone operation (if not suppressed) will download blobs for current versions of project files. The Git client knows how to batch those download requests to ask the server only for the missing blobs.

With blobless clone, you will trigger a blob download whenever you need the contents of the file. This means that git log, git merge-base, and other commands that do not examine file contents run without the need for additional download of blob objects.

Moreover, to examine if the file has been changed, Git can simply compare object IDs, and it doesn’t need to access the actual contents. Therefore, examining file history with git log -- <path> doesn’t need to download any objects either. This command runs with the same performance as in a full clone. This is the result of the fact that the object ID is based on the cryptographic hash of file contents (Git currently uses SHA-1 for this purpose).

Git commands such as git checkout / git switch, git reset --hard <revision>, and git merge need to download blobs to populate the working directory, the index (the staging area), or both. To compute diffs, Git also needs to have blobs to compare; therefore, commands such as git diff or git blame <path> might trigger blob downloads the first time they are run with specific arguments.

In some repositories, the tree data might be a significant portion of the repository’s size. This might happen if the repository has a large amount of files and directories and deep and wide directory hierarchies. In such cases, using a treeless clone with the --filter=tree:0 option might offer a better solution.

Note that any objects that are only referenced by those objects that were skipped due to the selected filter will also be missing. This means that the treeless clone is more sparse than the blobless clone (as only trees can point to blobs… well, a tag object can point to a blob object, but you won’t typically encounter this).

The advantage of a treeless clone over a blobless clone is a much faster initial clone and faster subsequent fetches. The disadvantage is that working in a treeless clone is more difficult because downloading a missing tree when needed is more expensive. It is also more difficult for the server to notice that the client already has some tree objects locally, so the request might send more data than necessary. Additionally, more commands require additional data to be downloaded. An example of this is git log -- <file>, which in the blobless clone could be run without the need to download anything extra. In a treeless clone, the command will start downloading trees for almost every commit in the history.

Treeless clones and submodules

The repositories that contain submodules (see Chapter 11, Managing Subprojects) may behave poorly with treeless clones. If you get too many tree download requests, you can either turn off the automatic fetching of submodules by ensuring that the fetch.recurseSubmodules configuration variable is set to false (or by using the --no-recurse-submodules option) or also filter submodules by setting the clone.filterSubmodules config option (or using the --recurse-submodules --filter=tree:0 --also-filter-submodules combination of command-line options).

Treeless clones are helpful for automatic builds, when you want to quickly clone the project, check out a single revision, compile it and/or run a test, and then throw away the repository (instead of using shallow clone). They are also useful if all you’re interested in is examining the history of the whole project.

The treeless clone is a special case of the depth-limited clone; the full syntax of the tree filter specification is --filter=tree:<depth>. In this case, the clone omits all blobs and trees whose depth from the root tree (from the top directory of the project) is greater than or equal to the specified limit. It can be easily seen that with <depth> being equal to 0 (that is, --filter=tree:0), the clone will not include any trees or blobs (except for those required for initial checkout).

Omitting large file contents with sparse clone

Section titled “Omitting large file contents with sparse clone”

The partial clone can also work as a tool to help you work with large files. This requires that the Git server (the Git hosting site) supports the specific type of filter. It also doesn’t remove the requirement that at least one remote repository must include those large files and their history so that you can download them on demand.

You can do this by providing the --filter=blob:limit=<size> option when you’re cloning, where <size> can include the k, m, and g suffixes. This will make Git omit blobs of the size at least <size> bytes, be it KiB, MiB, or GiB (depending on the suffix). For example, blob:limit=1k is the same as blob:limit=1024.

Matching clone sparsity to checkout sparsity

Section titled “Matching clone sparsity to checkout sparsity”

Modern Git includes basic support for the sparse clone filter, which makes it omit all blobs that would be not required for sparse checkout. For security reasons, however, support for the easier-to-use form of --filter=sparse:path=<path> was dropped from Git. The supported form is --filter=sparse:oid=<blob-ish>. This form is safe against the time of check to time of use problem, as opposed to the path-based form, because <blob-ish> (that is, a reference to a blob object) ultimately resolves to the object ID that defines its contents.

At the time of writing, you would be hard to find a Git server that supports this filter and doesn’t respond with warning: filtering not recognized by server, ignoring. But when it starts getting widely supported, one possible solution would be to create a tag for every sparse checkout pattern of interest, and then use the selected tag for blob-ish:

$ git sparse-checkout set <subdir>
$ git hash-object -t blob -w .git/info/sparse-checkout
bd177ff9527327c67f50c644c421d280bb8b55f5
$ git tag -a -m 'sparse-checkout pattern for <subdir>'
sparse/<subdir> bd177ff9527327c67f50c644c421d280bb8b55f5
$ git push origin tag sparse-checkout/<subdirectory>
To <repository url>
* [new tag] sparse/<subdir> -> sparse/<subdir>

Of course, in the third step, you need to use the SHA-1 that’s output from the previous command.

In this case, cloning would use the --filter=sparse:oid=sparse/<subdir>^{blob} option (where you would need to use the name of the tag that was created by the sequence of commands shown previously).

Faster checking for file changes with filesystem monitor

Section titled “Faster checking for file changes with filesystem monitor”

When you run a Git command that operates on the worktree, such as git status or git diff, Git has to discover what changed relative to the index, or relative to the specified revision. It does that by searching the entire worktree, which for repositories with a large number of files can take a long time. It also has to rediscover the same information from scratch every time you run such a command.

Filesystem monitor is a long-running daemon or a service process that does the following:

  • Registers with the operating system to watch specified directories and receive change notification events for directories and files of interest
  • Keeps the pathnames of those changed watched files and directories in some (in-memory) data structure that can be queried quickly
  • Responds to client requests for a list of files and directories that have been modified recently

Since version 2.37, Git includes the built-in file system monitor (FSMonitor) known as git fsmonitor--daemon. It is currently available on macOS and Windows. This daemon listens for IPC connections from client processes, such as git status, and sends a list of changed files over a Unix domain socket or a named pipe.

Turning it on is very simple; you just need to configure Git to use it. This can be done with the following command:

$ git config core.fsmonitor true

This monitor works well with core.untrackedCache, so it is recommended to set this configuration option to true as well.

You can query this daemon for the list of watched repositories:

$ git fsmonitor--daemon status
fsmonitor-daemon is watching 'C:/work/chromium'

If either the operating system or the filesystem the repository is on does not allow you to use this monitor, there is an option to use the hook-based file system monitor. This type of hook can be turned on by setting the core.fsmonitor config option to the path to the filesystem monitor hook. The hook must support the fsmonitor-watchman hook protocol, and when run return the list of changed files on standard output.

Git comes with the fsmonitor-watchman.sample file, which is installed inside the .git/hooks/ directory. Before turning it on, as described in the previous paragraph, rename it by removing the *.sample suffix. If the file is missing, you can download it from https://github.com/git/git/tree/master/templates. This hook requires the Watchman file’s watching service (https://facebook.github.io/watchman/) to be installed.

This chapter provided solutions to handling large Git repositories, from the use of the Scalar tool to specialized solutions.

First, you learned how to use shallow clone to download and operate on the selected shallow subset of the project history.

Then, you learned how to handle large files by storing them outside the repository or separating them into submodules. The problem of large data in data science projects was briefly mentioned, as were specialized solutions to this problem.

Finally, you learned how to manage large monorepos with sparse checkout, sparse clone, and filesystem monitor.

The next chapter will help you make Git easier to use and better fit it to your specific circumstances. This includes configuring repository maintenance, which is particularly important for making working with large repositories smooth.

Answer the following questions to test your knowledge of this chapter:

  1. What is the simplest solution to handling large repositories?
  2. How you can make cloning faster for repositories with a long history?
  3. How can you handle large files that are needed only by some developers?
  4. What techniques make working with repositories with large numbers of files faster?
  5. What’s the difference between shallow clone, sparse clone, and sparse checkout?

Here are the answers to this chapter’s questions:

  1. Use the built-in scalar tool, either using it to clone the repository or to register the given repository with the tool.
  2. You can use shallow clone or blobless sparse clone. In the first case, you would get a shortened history, while in the second case, the repository’s size will be smaller but some operations will require network access to download additional data.
  3. You can store large files outside the repository with Git-LFS or git-annex (or a similar solution). You can clone the repository without downloading large file data with the sparse clone feature.
  4. Use the sparse checkout feature if you’re only working inside a specific subdirectory, use sparse clone to reduce repository size, and use filesystem monitor (if possible) to make operations faster.
  5. Shallow clone only downloads selected part of the repository history, and all local operations are limited to this selection, though it is easy to change the depth of the history. Sparse clone reduces repository size by downloading only a selected subset of objects, fetching those objects on demand, as their presence becomes necessary to perform operations. Sparse checkout reduces the number of checked-out files, making the working directory smaller (and operations faster).

To learn more about the topics that were covered in this chapter, take a look at the following resources: