Published 2025-01-06.
Time to read: 6 minutes.
git
collection.
I have published 5 articles about the Git large file system (LFS). They are meant to be read in order.
- Git Large File System Overview
- Git LFS Client Installation
- Git LFS Server URLs
- Git LFS Filename Patterns & Tracking
- Git LFS Client Configuration & Commands
- Working With Git LFS
- Evaluation Procedure For Git LFS Servers
7 articles are still in process.
Instructions for typing along are given for Ubuntu and WSL/Ubuntu. If you have a Mac, most of this information should be helpful.
This Page Probably Contains Errors
This page is incomplete and may contain errors. Several unanswered questions are shown on this page. It has been published to allow collaboration with fact-checkers. Do not rely on this information yet.
Wildmatch
Git LFS can manage specific files, or all files whose name matches a pattern.
The patterns supported by Git LFS are the same as those supported by .gitignore
,
with the exception that negative patterns are not supported.
The specification for the filenames that are to be stored in LFS is called a wildmatch
.
Patterns
Package wildmatch
is a reimplementation of Git’s wildmatch.c
-style filepath pattern matching.
I show its documentation here because this is the best documentation for Git’s filename matching syntax.
Wildmatch patterns are comprised of any combination of the following three components:
- String literals. A string literal is "foo", or "foo\*" (matching "foo", and "foo\", respectively). In general, string literals match their exact contents in a filepath, and cannot match over directories unless they include the operating system-specific path separator.
- Wildcards. There are three types of wildcards:
- Single-asterisk ('*'): matches any combination of characters, any number of times. Does not match path separators.
- Single-question mark ('?'): matches any single character, but not a path separator.
- Double-asterisk ('**'): greedily matches any number of directories. For example, '**/foo' matches '/foo', 'bar/baz/woot/foot', but not 'foo/bar'. Double-asterisks must be separated by filepath separators on either side.
- Character groups. A character group is composed of a set of included and excluded character types. The set of included character types begins the character group, and a '^' or '!' separates it from the set of excluded character types.
-
A character type can be one of the following:
- Character literal: a single character, i.e., 'c'.
- Character group: a group of characters, i.e., '[:alnum:]', etc.
- Character range: a range of characters, i.e., 'a-z'.
A Wildmatch pattern can be any combination of the above components, in any ordering, and repeated any number of times.
File Name Case Sensitivity
By default, Git is case-sensitive, but the underlying file systems (like NTFS on Windows and HFS+ on macOS) can be case-insensitive.
Wildcard patterns are case-sensitive. Some Windows programs generate files whose names are in upper case. That means you might need to define two patterns: an upper case pattern and a lower case pattern. It is a good habit to define both at the same time.
You could disable case sensitivity for the current repository, however, doing so might introduce problems.
$ git config core.ignorecase true
You can disable file name case sensitivity for all repositories for this OS user account, but again, doing so may invite problems:
$ git config --global core.ignorecase true
Instead of disabling file name case sensitivity, I suggest you get in the habit of declaring two versions of every wildmatch pattern: one in upper case and one in lower case. I show an example of that below.
.gitattributes
Wildmatch incantations are stored in files called
.gitattributes
.
These files should be checked into git.
Although a single .gitattributes
file is often stored at the top of a git repository,
any number of files with that name could also be stored in arbitrary subdirectories of a git repository.
Having multiple .gitattributes
files would allow a project to have different
wildmatch
patterns for various portions of the git repository.
It is also possible to have a system-wide .gitattributes
file.
The following incantation uses
the git var
command
to display the path for it:
$ git var GIT_ATTR_SYSTEM /etc/gitattributes
The man page for gitattributes
is:
GITATTRIBUTES(5) Git Manual GITATTRIBUTES(5)
NAME gitattributes - Defining attributes per path
SYNOPSIS $GIT_DIR/info/attributes, .gitattributes
DESCRIPTION A gitattributes file is a simple text file that gives attributes to pathnames.
Each line in gitattributes file is of form:
pattern attr1 attr2 ...
That is, a pattern followed by an attributes list, separated by whitespaces. Leading and trailing whitespaces are ignored. Lines that begin with # are ignored. Patterns that begin with a double quote are quoted in C style. When the pattern matches the path in question, the attributes listed on the line are given to the path.
Each attribute can be in one of these states for a given path:
Set The path has the attribute with special value "true"; this is specified by listing only the name of the attribute in the attribute list.
Unset The path has the attribute with special value "false"; this is specified by listing the name of the attribute prefixed with a dash - in the attribute list.
Set to a value The path has the attribute with specified string value; this is specified by listing the name of the attribute followed by an equal sign = and its value in the attribute list.
Unspecified No pattern matches the path, and nothing says if the path has or does not have the attribute, the attribute for the path is said to be Unspecified.
When more than one pattern matches the path, a later line overrides an earlier line. This overriding is done per attribute.
The rules by which the pattern matches paths are the same as in .gitignore files (see gitignore(5)), with a few exceptions:
• negative patterns are forbidden
• patterns that match a directory do not recursively match paths inside that directory (so using the trailing-slash path/ syntax is pointless in an attributes file; use path/** instead)
When deciding what attributes are assigned to a path, Git consults $GIT_DIR/info/attributes file (which has the highest precedence), .gitattributes file in the same directory as the path in question, and its parent directories up to the toplevel of the work tree (the further the directory that contains .gitattributes is from the path in question, the lower its precedence). Finally global and system-wide files are considered (they have the lowest precedence).
When the .gitattributes file is missing from the work tree, the path in the index is used as a fall-back. During checkout process, .gitattributes in the index is used and then the file in the working tree is used as a fall-back.
If you wish to affect only a single repository (i.e., to assign attributes to files that are particular to one user’s workflow for that repository), then attributes should be placed in the $GIT_DIR/info/attributes file. Attributes which should be version-controlled and distributed to other repositories (i.e., attributes of interest to all users) should go into .gitattributes files. Attributes that should affect all repositories for a single user should be placed in a file specified by the core.attributesFile configuration option (see git-config(1)). Its default value is $XDG_CONFIG_HOME/git/attributes. If $XDG_CONFIG_HOME is either not set or empty, $HOME/.config/git/attributes is used instead. Attributes for all users on a system should be placed in the $(prefix)/etc/gitattributes file.
Sometimes you would need to override a setting of an attribute for a path to Unspecified state. This can be done by listing the name of the attribute prefixed with an exclamation point !.
RESERVED BUILTIN_* ATTRIBUTES builtin_* is a reserved namespace for builtin attribute values. Any user defined attributes under this namespace will be ignored and trigger a warning.
builtin_objectmode This attribute is for filtering files by their file bit modes (40000, 120000, 160000, 100755, 100644). e.g. :(attr:builtin_objectmode=160000). You may also check these values with git check-attr builtin_objectmode -- <file>. If the object is not in the index git check-attr --cached will return unspecified.
EFFECTS Certain operations by Git can be influenced by assigning particular attributes to a path. Currently, the following operations are attributes-aware.
Checking-out and checking-in These attributes affect how the contents stored in the repository are copied to the working tree files when commands such as git switch, git checkout and git merge run. They also affect how Git stores the contents you prepare in the working tree in the repository upon git add and git commit.
text
This attribute marks the path as a text file, which enables end-of-line conversion: When a matching file is added to the index, the file’s line endings are normalized to LF in the index. Conversely, when the file is copied from the index to the working directory, its line endings may be converted from LF to CRLF depending on the eol attribute, the Git config, and the platform (see explanation of eol below).
Set Setting the text attribute on a path enables end-of-line conversion on checkin and checkout as described above. Line endings are normalized to LF in the index every time the file is checked in, even if the file was previously added to Git with CRLF line endings.
Unset Unsetting the text attribute on a path tells Git not to attempt any end-of-line conversion upon checkin or checkout.
Set to string value "auto" When text is set to "auto", Git decides by itself whether the file is text or binary. If it is text and the file was not already in Git with CRLF endings, line endings are converted on checkin and checkout as described above. Otherwise, no conversion is done on checkin or checkout.
Unspecified If the text attribute is unspecified, Git uses the core.autocrlf configuration variable to determine if the file should be converted.
Any other value causes Git to act as if text has been left unspecified.
eol
This attribute marks a path to use a specific line-ending style in the working tree when it is checked out. It has effect only if text or text=auto is set (see above), but specifying eol automatically sets text if text was left unspecified.
Set to string value "crlf" This setting converts the file’s line endings in the working directory to CRLF when the file is checked out.
Set to string value "lf" This setting uses the same line endings in the working directory as in the index when the file is checked out.
Unspecified If the eol attribute is unspecified for a file, its line endings in the working directory are determined by the core.autocrlf or core.eol configuration variable (see the definitions of those options in git-config(1)). If text is set but neither of those variables is, the default is eol=crlf on Windows and eol=lf on all other platforms.
Backwards compatibility with crlf attribute
For backwards compatibility, the crlf attribute is interpreted as follows:
crlf text -crlf -text crlf=input eol=lf
End-of-line conversion
While Git normally leaves file contents alone, it can be configured to normalize line endings to LF in the repository and, optionally, to convert them to CRLF when files are checked out.
If you simply want to have CRLF line endings in your working directory regardless of the repository you are working with, you can set the config variable "core.autocrlf" without using any attributes.
[core] autocrlf = true
This does not force normalization of text files, but does ensure that text files that you introduce to the repository have their line endings normalized to LF when they are added, and that files that are already normalized in the repository stay normalized.
If you want to ensure that text files that any contributor introduces to the repository have their line endings normalized, you can set the text attribute to "auto" for all files.
* text=auto
The attributes allow a fine-grained control, how the line endings are converted. Here is an example that will make Git normalize .txt, .vcproj and .sh files, ensure that .vcproj files have CRLF and .sh files have LF in the working directory, and prevent .jpg files from being normalized regardless of their content.
* text=auto *.txt text *.vcproj text eol=crlf *.sh text eol=lf *.jpg -text
Note
When text=auto conversion is enabled in a cross-platform project using push and pull to a central repository the text files containing CRLFs should be normalized.
From a clean working directory:
$ echo "* text=auto" >.gitattributes $ git add --renormalize . $ git status # Show files that will be normalized $ git commit -m "Introduce end-of-line normalization"
If any files that should not be normalized show up in git status, unset their text attribute before running git add -u.
manual.pdf -text
Conversely, text files that Git does not detect can have normalization enabled manually.
weirdchars.txt text
If core.safecrlf is set to "true" or "warn", Git verifies if the conversion is reversible for the current setting of core.autocrlf. For "true", Git rejects irreversible conversions; for "warn", Git only prints a warning but accepts an irreversible conversion. The safety triggers to prevent such a conversion done to the files in the work tree, but there are a few exceptions. Even though...
• git add itself does not touch the files in the work tree, the next checkout would, so the safety triggers;
• git apply to update a text file with a patch does touch the files in the work tree, but the operation is about text files and CRLF conversion is about fixing the line ending inconsistencies, so the safety does not trigger;
• git diff itself does not touch the files in the work tree, it is often run to inspect the changes you intend to next git add. To catch potential problems early, safety triggers.
working-tree-encoding
Git recognizes files encoded in ASCII or one of its supersets (e.g. UTF-8, ISO-8859-1, ...) as text files. Files encoded in certain other encodings (e.g. UTF-16) are interpreted as binary and consequently built-in Git text processing tools (e.g. git diff) as well as most Git web front ends do not visualize the contents of these files by default.
In these cases you can tell Git the encoding of a file in the working directory with the working-tree-encoding attribute. If a file with this attribute is added to Git, then Git re-encodes the content from the specified encoding to UTF-8. Finally, Git stores the UTF-8 encoded content in its internal data structure (called "the index"). On checkout the content is re-encoded back to the specified encoding.
Please note that using the working-tree-encoding attribute may have a number of pitfalls:
• Alternative Git implementations (e.g. JGit or libgit2) and older Git versions (as of March 2018) do not support the working-tree-encoding attribute. If you decide to use the working-tree-encoding attribute in your repository, then it is strongly recommended to ensure that all clients working with the repository support it.
For example, Microsoft Visual Studio resources files (*.rc) or PowerShell script files (*.ps1) are sometimes encoded in UTF-16. If you declare *.ps1 as files as UTF-16 and you add foo.ps1 with a working-tree-encoding enabled Git client, then foo.ps1 will be stored as UTF-8 internally. A client without working-tree-encoding support will checkout foo.ps1 as UTF-8 encoded file. This will typically cause trouble for the users of this file.
If a Git client that does not support the working-tree-encoding attribute adds a new file bar.ps1, then bar.ps1 will be stored "as-is" internally (in this example probably as UTF-16). A client with working-tree-encoding support will interpret the internal contents as UTF-8 and try to convert it to UTF-16 on checkout. That operation will fail and cause an error.
• Reencoding content to non-UTF encodings can cause errors as the conversion might not be UTF-8 round trip safe. If you suspect your encoding to not be round trip safe, then add it to core.checkRoundtripEncoding to make Git check the round trip encoding (see git-config(1)). SHIFT-JIS (Japanese character set) is known to have round trip issues with UTF-8 and is checked by default.
• Reencoding content requires resources that might slow down certain Git operations (e.g git checkout or git add).
Use the working-tree-encoding attribute only if you cannot store a file in UTF-8 encoding and if you want Git to be able to process the content as text.
As an example, use the following attributes if your *.ps1 files are UTF-16 encoded with byte order mark (BOM) and you want Git to perform automatic line ending conversion based on your platform.
*.ps1 text working-tree-encoding=UTF-16
Use the following attributes if your *.ps1 files are UTF-16 little endian encoded without BOM and you want Git to use Windows line endings in the working directory (use UTF-16LE-BOM instead of UTF-16LE if you want UTF-16 little endian with BOM). Please note, it is highly recommended to explicitly define the line endings with eol if the working-tree-encoding attribute is used to avoid ambiguity.
*.ps1 text working-tree-encoding=UTF-16LE eol=crlf
You can get a list of all available encodings on your platform with the following command:
iconv --list
If you do not know the encoding of a file, then you can use the file command to guess the encoding:
file foo.ps1
ident
When the attribute ident is set for a path, Git replaces $Id$ in the blob object with $Id:, followed by the 40-character hexadecimal blob object name, followed by a dollar sign $ upon checkout. Any byte sequence that begins with $Id: and ends with $ in the worktree file is replaced with $Id$ upon check-in.
filter
A filter attribute can be set to a string value that names a filter driver specified in the configuration.
A filter driver consists of a clean command and a smudge command, either of which can be left unspecified. Upon checkout, when the smudge command is specified, the command is fed the blob object from its standard input, and its standard output is used to update the worktree file. Similarly, the clean command is used to convert the contents of worktree file upon checkin. By default these commands process only a single blob and terminate. If a long running process filter is used in place of clean and/or smudge filters, then Git can process all blobs with a single filter command invocation for the entire life of a single Git command, for example git add --all. If a long running process filter is configured then it always takes precedence over a configured single blob filter. See section below for the description of the protocol used to communicate with a process filter.
One use of the content filtering is to massage the content into a shape that is more convenient for the platform, filesystem, and the user to use. For this mode of operation, the key phrase here is "more convenient" and not "turning something unusable into usable". In other words, the intent is that if someone unsets the filter driver definition, or does not have the appropriate filter program, the project should still be usable.
Another use of the content filtering is to store the content that cannot be directly used in the repository (e.g. a UUID that refers to the true content stored outside Git, or an encrypted content) and turn it into a usable form upon checkout (e.g. download the external content, or decrypt the encrypted content).
These two filters behave differently, and by default, a filter is taken as the former, massaging the contents into more convenient shape. A missing filter driver definition in the config, or a filter driver that exits with a non-zero status, is not an error but makes the filter a no-op passthru.
You can declare that a filter turns a content that by itself is unusable into a usable content by setting the filter.<driver>.required configuration variable to true.
Note: Whenever the clean filter is changed, the repo should be renormalized: $ git add --renormalize .
For example, in .gitattributes, you would assign the filter attribute for paths.
*.c filter=indent
Then you would define a "filter.indent.clean" and "filter.indent.smudge" configuration in your .git/config to specify a pair of commands to modify the contents of C programs when the source files are checked in ("clean" is run) and checked out (no change is made because the command is "cat").
[filter "indent"] clean = indent smudge = cat
For best results, clean should not alter its output further if it is run twice ("clean→clean" should be equivalent to "clean"), and multiple smudge commands should not alter clean's output ("smudge→smudge→clean" should be equivalent to "clean"). See the section on merging below.
The "indent" filter is well-behaved in this regard: it will not modify input that is already correctly indented. In this case, the lack of a smudge filter means that the clean filter must accept its own output without modifying it.
If a filter must succeed in order to make the stored contents usable, you can declare that the filter is required, in the configuration:
[filter "crypt"] clean = openssl enc ... smudge = openssl enc -d ... required
Sequence "%f" on the filter command line is replaced with the name of the file the filter is working on. A filter might use this in keyword substitution. For example:
[filter "p4"] clean = git-p4-filter --clean %f smudge = git-p4-filter --smudge %f
Note that "%f" is the name of the path that is being worked on. Depending on the version that is being filtered, the corresponding file on disk may not exist, or may have different contents. So, smudge and clean commands should not try to access the file on disk, but only act as filters on the content provided to them on standard input.
Long Running Filter Process
If the filter command (a string value) is defined via filter.<driver>.process then Git can process all blobs with a single filter invocation for the entire life of a single Git command. This is achieved by using the long-running process protocol (described in technical/long-running-process-protocol.txt).
When Git encounters the first file that needs to be cleaned or smudged, it starts the filter and performs the handshake. In the handshake, the welcome message sent by Git is "git-filter-client", only version 2 is supported, and the supported capabilities are "clean", "smudge", and "delay".
Afterwards Git sends a list of "key=value" pairs terminated with a flush packet. The list will contain at least the filter command (based on the supported capabilities) and the pathname of the file to filter relative to the repository root. Right after the flush packet Git sends the content split in zero or more pkt-line packets and a flush packet to terminate content. Please note, that the filter must not send any response before it received the content and the final flush packet. Also note that the "value" of a "key=value" pair can contain the "=" character whereas the key would never contain that character.
packet: git> command=smudge packet: git> pathname=path/testfile.dat packet: git> 0000 packet: git> CONTENT packet: git> 0000
The filter is expected to respond with a list of "key=value" pairs terminated with a flush packet. If the filter does not experience problems then the list must contain a "success" status. Right after these packets the filter is expected to send the content in zero or more pkt-line packets and a flush packet at the end. Finally, a second list of "key=value" pairs terminated with a flush packet is expected. The filter can change the status in the second list or keep the status as is with an empty list. Please note that the empty list must be terminated with a flush packet regardless.
packet: git< status=success packet: git< 0000 packet: git< SMUDGED_CONTENT packet: git< 0000 packet: git< 0000 # empty list, keep "status=success" unchanged!
If the result content is empty then the filter is expected to respond with a "success" status and a flush packet to signal the empty content.
packet: git< status=success packet: git< 0000 packet: git< 0000 # empty content! packet: git< 0000 # empty list, keep "status=success" unchanged!
In case the filter cannot or does not want to process the content, it is expected to respond with an "error" status.
packet: git< status=error packet: git< 0000
If the filter experiences an error during processing, then it can send the status "error" after the content was (partially or completely) sent.
packet: git< status=success packet: git< 0000 packet: git< HALF_WRITTEN_ERRONEOUS_CONTENT packet: git< 0000 packet: git< status=error packet: git< 0000
In case the filter cannot or does not want to process the content as well as any future content for the lifetime of the Git process, then it is expected to respond with an "abort" status at any point in the protocol.
packet: git< status=abort packet: git< 0000
Git neither stops nor restarts the filter process in case the "error"/"abort" status is set. However, Git sets its exit code according to the filter.<driver>.required flag, mimicking the behavior of the filter.<driver>.clean / filter.<driver>.smudge mechanism.
If the filter dies during the communication or does not adhere to the protocol then Git will stop the filter process and restart it with the next file that needs to be processed. Depending on the filter.<driver>.required flag Git will interpret that as error.
Delay
If the filter supports the "delay" capability, then Git can send the flag "can-delay" after the filter command and pathname. This flag denotes that the filter can delay filtering the current blob (e.g. to compensate network latencies) by responding with no content but with the status "delayed" and a flush packet.
packet: git> command=smudge packet: git> pathname=path/testfile.dat packet: git> can-delay=1 packet: git> 0000 packet: git> CONTENT packet: git> 0000 packet: git< status=delayed packet: git< 0000
If the filter supports the "delay" capability then it must support the "list_available_blobs" command. If Git sends this command, then the filter is expected to return a list of pathnames representing blobs that have been delayed earlier and are now available. The list must be terminated with a flush packet followed by a "success" status that is also terminated with a flush packet. If no blobs for the delayed paths are available, yet, then the filter is expected to block the response until at least one blob becomes available. The filter can tell Git that it has no more delayed blobs by sending an empty list. As soon as the filter responds with an empty list, Git stops asking. All blobs that Git has not received at this point are considered missing and will result in an error.
packet: git> command=list_available_blobs packet: git> 0000 packet: git< pathname=path/testfile.dat packet: git< pathname=path/otherfile.dat packet: git< 0000 packet: git< status=success packet: git< 0000
After Git received the pathnames, it will request the corresponding blobs again. These requests contain a pathname and an empty content section. The filter is expected to respond with the smudged content in the usual way as explained above.
packet: git> command=smudge packet: git> pathname=path/testfile.dat packet: git> 0000 packet: git> 0000 # empty content! packet: git< status=success packet: git< 0000 packet: git< SMUDGED_CONTENT packet: git< 0000 packet: git< 0000 # empty list, keep "status=success" unchanged!
Example
A long running filter demo implementation can be found in contrib/long-running-filter/example.pl located in the Git core repository. If you develop your own long running filter process then the GIT_TRACE_PACKET environment variables can be very helpful for debugging (see git(1)).
Please note that you cannot use an existing filter.<driver>.clean or filter.<driver>.smudge command with filter.<driver>.process because the former two use a different inter process communication protocol than the latter one.
Interaction between checkin/checkout attributes
In the check-in codepath, the worktree file is first converted with filter driver (if specified and corresponding driver defined), then the result is processed with ident (if specified), and then finally with text (again, if specified and applicable).
In the check-out codepath, the blob content is first converted with text, and then ident and fed to filter.
Merging branches with differing checkin/checkout attributes
If you have added attributes to a file that cause the canonical repository format for that file to change, such as adding a clean/smudge filter or text/eol/ident attributes, merging anything where the attribute is not in place would normally cause merge conflicts.
To prevent these unnecessary merge conflicts, Git can be told to run a virtual check-out and check-in of all three stages of a file when resolving a three-way merge by setting the merge.renormalize configuration variable. This prevents changes caused by check-in conversion from causing spurious merge conflicts when a converted file is merged with an unconverted file.
As long as a "smudge→clean" results in the same output as a "clean" even on files that are already smudged, this strategy will automatically resolve all filter-related conflicts. Filters that do not act in this way may cause additional merge conflicts that must be resolved manually.
Generating diff text diff
The attribute diff affects how Git generates diffs for particular files. It can tell Git whether to generate a textual patch for the path or to treat the path as a binary file. It can also affect what line is shown on the hunk header @@ -k,l +n,m @@ line, tell Git to use an external command to generate the diff, or ask Git to convert binary files to a text format before generating the diff.
Set A path to which the diff attribute is set is treated as text, even when they contain byte values that normally never appear in text files, such as NUL.
Unset A path to which the diff attribute is unset will generate Binary files differ (or a binary patch, if binary patches are enabled).
Unspecified A path to which the diff attribute is unspecified first gets its contents inspected, and if it looks like text and is smaller than core.bigFileThreshold, it is treated as text. Otherwise it would generate Binary files differ.
String Diff is shown using the specified diff driver. Each driver may specify one or more options, as described in the following section. The options for the diff driver "foo" are defined by the configuration variables in the "diff.foo" section of the Git config file.
Defining an external diff driver
The definition of a diff driver is done in gitconfig, not gitattributes file, so strictly speaking this manual page is a wrong place to talk about it. However...
To define an external diff driver jcdiff, add a section to your $GIT_DIR/config file (or $HOME/.gitconfig file) like this:
[diff "jcdiff"] command = j-c-diff
When Git needs to show you a diff for the path with diff attribute set to jcdiff, it calls the command you specified with the above configuration, i.e. j-c-diff, with 7 parameters, just like GIT_EXTERNAL_DIFF program is called. See git(1) for details.
If the program is able to ignore certain changes (similar to git diff --ignore-space-change), then also set the option trustExitCode to true. It is then expected to return exit code 1 if it finds significant changes and 0 if it doesn’t.
Setting the internal diff algorithm
The diff algorithm can be set through the diff.algorithm config key, but sometimes it may be helpful to set the diff algorithm per path. For example, one may want to use the minimal diff algorithm for .json files, and the histogram for .c files, and so on without having to pass in the algorithm through the command line each time.
First, in .gitattributes, assign the diff attribute for paths.
*.json diff=<name>
Then, define a "diff.<name>.algorithm" configuration to specify the diff algorithm, choosing from myers, patience, minimal, or histogram.
[diff "<name>"] algorithm = histogram
This diff algorithm applies to user facing diff output like git-diff(1), git-show(1) and is used for the --stat output as well. The merge machinery will not use the diff algorithm set through this method.
Note
If diff.<name>.command is defined for path with the diff=<name> attribute, it is executed as an external diff driver (see above), and adding diff.<name>.algorithm has no effect, as the algorithm is not passed to the external diff driver.
Defining a custom hunk-header
Each group of changes (called a "hunk") in the textual diff output is prefixed with a line of the form:
@@ -k,l +n,m @@ TEXT
This is called a hunk header. The "TEXT" portion is by default a line that begins with an alphabet, an underscore or a dollar sign; this matches what GNU diff -p output uses. This default selection however is not suited for some contents, and you can use a customized pattern to make a selection.
First, in .gitattributes, you would assign the diff attribute for paths.
*.tex diff=tex
Then, you would define a "diff.tex.xfuncname" configuration to specify a regular expression that matches a line that you would want to appear as the hunk header "TEXT". Add a section to your $GIT_DIR/config file (or $HOME/.gitconfig file) like this:
[diff "tex"] xfuncname = "^(\\\\(sub)*section\\{.*)$"
Note. A single level of backslashes are eaten by the configuration file parser, so you would need to double the backslashes; the pattern above picks a line that begins with a backslash, and zero or more occurrences of sub followed by section followed by open brace, to the end of line.
There are a few built-in patterns to make this easier, and tex is one of them, so you do not have to write the above in your configuration file (you still need to enable this with the attribute mechanism, via .gitattributes). The following built in patterns are available:
• ada suitable for source code in the Ada language.
• bash suitable for source code in the Bourne-Again SHell language. Covers a superset of POSIX shell function definitions.
• bibtex suitable for files with BibTeX coded references.
• cpp suitable for source code in the C and C++ languages.
• csharp suitable for source code in the C# language.
• css suitable for cascading style sheets.
• dts suitable for devicetree (DTS) files.
• elixir suitable for source code in the Elixir language.
• fortran suitable for source code in the Fortran language.
• fountain suitable for Fountain documents.
• golang suitable for source code in the Go language.
• html suitable for HTML/XHTML documents.
• java suitable for source code in the Java language.
• kotlin suitable for source code in the Kotlin language.
• markdown suitable for Markdown documents.
• matlab suitable for source code in the MATLAB and Octave languages.
• objc suitable for source code in the Objective-C language.
• pascal suitable for source code in the Pascal/Delphi language.
• perl suitable for source code in the Perl language.
• php suitable for source code in the PHP language.
• python suitable for source code in the Python language.
• ruby suitable for source code in the Ruby language.
• rust suitable for source code in the Rust language.
• scheme suitable for source code in the Scheme language.
• tex suitable for source code for LaTeX documents.
Customizing word diff
You can customize the rules that git diff --word-diff uses to split words in a line, by specifying an appropriate regular expression in the "diff.*.wordRegex" configuration variable. For example, in TeX a backslash followed by a sequence of letters forms a command, but several such commands can be run together without intervening whitespace. To separate them, use a regular expression in your $GIT_DIR/config file (or $HOME/.gitconfig file) like this:
[diff "tex"] wordRegex = "\\\\[a-zA-Z]+|[{}]|\\\\.|[^\\{}[:space:]]+"
A built-in pattern is provided for all languages listed in the previous section.
Performing text diffs of binary files
Sometimes it is desirable to see the diff of a text-converted version of some binary files. For example, a word processor document can be converted to an ASCII text representation, and the diff of the text shown. Even though this conversion loses some information, the resulting diff is useful for human viewing (but cannot be applied directly).
The textconv config option is used to define a program for performing such a conversion. The program should take a single argument, the name of a file to convert, and produce the resulting text on stdout.
For example, to show the diff of the exif information of a file instead of the binary information (assuming you have the exif tool installed), add the following section to your $GIT_DIR/config file (or $HOME/.gitconfig file):
[diff "jpg"] textconv = exif
Note
The text conversion is generally a one-way conversion; in this example, we lose the actual image contents and focus just on the text data. This means that diffs generated by textconv are not suitable for applying. For this reason, only git diff and the git log family of commands (i.e., log, whatchanged, show) will perform text conversion. git format-patch will never generate this output. If you want to send somebody a text-converted diff of a binary file (e.g., because it quickly conveys the changes you have made), you should generate it separately and send it as a comment in addition to the usual binary diff that you might send.
Because text conversion can be slow, especially when doing a large number of them with git log -p, Git provides a mechanism to cache the output and use it in future diffs. To enable caching, set the "cachetextconv" variable in your diff driver’s config. For example:
[diff "jpg"] textconv = exif cachetextconv = true
This will cache the result of running "exif" on each blob indefinitely. If you change the textconv config variable for a diff driver, Git will automatically invalidate the cache entries and re-run the textconv filter. If you want to invalidate the cache manually (e.g., because your version of "exif" was updated and now produces better output), you can remove the cache manually with git update-ref -d refs/notes/textconv/jpg (where "jpg" is the name of the diff driver, as in the example above).
Choosing textconv versus external diff
If you want to show differences between binary or specially-formatted blobs in your repository, you can choose to use either an external diff command, or to use textconv to convert them to a diff-able text format. Which method you choose depends on your exact situation.
The advantage of using an external diff command is flexibility. You are not bound to find line-oriented changes, nor is it necessary for the output to resemble unified diff. You are free to locate and report changes in the most appropriate way for your data format.
A textconv, by comparison, is much more limiting. You provide a transformation of the data into a line-oriented text format, and Git uses its regular diff tools to generate the output. There are several advantages to choosing this method:
1. Ease of use. It is often much simpler to write a binary to text transformation than it is to perform your own diff. In many cases, existing programs can be used as textconv filters (e.g., exif, odt2txt).
2. Git diff features. By performing only the transformation step yourself, you can still utilize many of Git’s diff features, including colorization, word-diff, and combined diffs for merges.
3. Caching. Textconv caching can speed up repeated diffs, such as those you might trigger by running git log -p.
Marking files as binary
Git usually guesses correctly whether a blob contains text or binary data by examining the beginning of the contents. However, sometimes you may want to override its decision, either because a blob contains binary data later in the file, or because the content, while technically composed of text characters, is opaque to a human reader. For example, many postscript files contain only ASCII characters, but produce noisy and meaningless diffs.
The simplest way to mark a file as binary is to unset the diff attribute in the .gitattributes file:
*.ps -diff
This will cause Git to generate Binary files differ (or a binary patch, if binary patches are enabled) instead of a regular diff.
However, one may also want to specify other diff driver attributes. For example, you might want to use textconv to convert postscript files to an ASCII representation for human viewing, but otherwise treat them as binary files. You cannot specify both -diff and diff=ps attributes. The solution is to use the diff.*.binary config option:
[diff "ps"] textconv = ps2ascii binary = true
Performing a three-way merge merge
The attribute merge affects how three versions of a file are merged when a file-level merge is necessary during git merge, and other commands such as git revert and git cherry-pick.
Set Built-in 3-way merge driver is used to merge the contents in a way similar to merge command of RCS suite. This is suitable for ordinary text files.
Unset Take the version from the current branch as the tentative merge result, and declare that the merge has conflicts. This is suitable for binary files that do not have a well-defined merge semantics.
Unspecified By default, this uses the same built-in 3-way merge driver as is the case when the merge attribute is set. However, the merge.default configuration variable can name different merge driver to be used with paths for which the merge attribute is unspecified.
String 3-way merge is performed using the specified custom merge driver. The built-in 3-way merge driver can be explicitly specified by asking for "text" driver; the built-in "take the current branch" driver can be requested with "binary".
Built-in merge drivers
There are a few built-in low-level merge drivers defined that can be asked for via the merge attribute.
text Usual 3-way file level merge for text files. Conflicted regions are marked with conflict markers <<<<<<<, ======= and >>>>>>>. The version from your branch appears before the ======= marker, and the version from the merged branch appears after the ======= marker.
binary Keep the version from your branch in the work tree, but leave the path in the conflicted state for the user to sort out.
union Run 3-way file level merge for text files, but take lines from both versions, instead of leaving conflict markers. This tends to leave the added lines in the resulting file in random order and the user should verify the result. Do not use this if you do not understand the implications.
Defining a custom merge driver
The definition of a merge driver is done in the .git/config file, not in the gitattributes file, so strictly speaking this manual page is a wrong place to talk about it. However...
To define a custom merge driver filfre, add a section to your $GIT_DIR/config file (or $HOME/.gitconfig file) like this:
[merge "filfre"] name = feel-free merge driver driver = filfre %O %A %B %L %P recursive = binary
The merge.*.name variable gives the driver a human-readable name.
The ‘merge.*.driver` variable’s value is used to construct a command to run to common ancestor’s version (%O), current version (%A) and the other branches’ version (%B). These three tokens are replaced with the names of temporary files that hold the contents of these versions when the command line is built. Additionally, %L will be replaced with the conflict marker size (see below).
The merge driver is expected to leave the result of the merge in the file named with %A by overwriting it, and exit with zero status if it managed to merge them cleanly, or non-zero if there were conflicts. When the driver crashes (e.g. killed by SEGV), it is expected to exit with non-zero status that are higher than 128, and in such a case, the merge results in a failure (which is different from producing a conflict).
The merge.*.recursive variable specifies what other merge driver to use when the merge driver is called for an internal merge between common ancestors, when there are more than one. When left unspecified, the driver itself is used for both internal merge and the final merge.
The merge driver can learn the pathname in which the merged result will be stored via placeholder %P. The conflict labels to be used for the common ancestor, local head and other head can be passed by using %S, %X and '%Y` respectively.
conflict-marker-size
This attribute controls the length of conflict markers left in the work tree file during a conflicted merge. Only a positive integer has a meaningful effect.
For example, this line in .gitattributes can be used to tell the merge machinery to leave much longer (instead of the usual 7-character-long) conflict markers when merging the file Documentation/git-merge.txt results in a conflict.
Documentation/git-merge.txt conflict-marker-size=32
Checking whitespace errors whitespace
The core.whitespace configuration variable allows you to define what diff and apply should consider whitespace errors for all paths in the project (See git-config(1)). This attribute gives you finer control per path.
Set Notice all types of potential whitespace errors known to Git. The tab width is taken from the value of the core.whitespace configuration variable.
Unset Do not notice anything as error.
Unspecified Use the value of the core.whitespace configuration variable to decide what to notice as error.
String Specify a comma separated list of common whitespace problems to notice in the same format as the core.whitespace configuration variable.
Creating an archive export-ignore
Files and directories with the attribute export-ignore won’t be added to archive files.
export-subst
If the attribute export-subst is set for a file then Git will expand several placeholders when adding this file to an archive. The expansion depends on the availability of a commit ID, i.e., if git-archive(1) has been given a tree instead of a commit or a tag then no replacement will be done. The placeholders are the same as those for the option --pretty=format: of git-log(1), except that they need to be wrapped like this: $Format:PLACEHOLDERS$ in the file. E.g. the string $Format:%H$ will be replaced by the commit hash. However, only one %(describe) placeholder is expanded per archive to avoid denial-of-service attacks.
Packing objects delta
Delta compression will not be attempted for blobs for paths with the attribute delta set to false.
Viewing files in GUI tools encoding
The value of this attribute specifies the character encoding that should be used by GUI tools (e.g. gitk(1) and git- gui(1)) to display the contents of the relevant file. Note that due to performance considerations gitk(1) does not use this attribute unless you manually enable per-file encodings in its options.
If this attribute is not set or has an invalid value, the value of the gui.encoding configuration variable is used instead (See git-config(1)).
USING MACRO ATTRIBUTES You do not want any end-of-line conversions applied to, nor textual diffs produced for, any binary file you track. You would need to specify e.g.
*.jpg -text -diff
but that may become cumbersome, when you have many attributes. Using macro attributes, you can define an attribute that, when set, also sets or unsets a number of other attributes at the same time. The system knows a built-in macro attribute, binary:
*.jpg binary
Setting the "binary" attribute also unsets the "text" and "diff" attributes as above. Note that macro attributes can only be "Set", though setting one might have the effect of setting or unsetting other attributes or even returning other attributes to the "Unspecified" state.
DEFINING MACRO ATTRIBUTES Custom macro attributes can be defined only in top-level gitattributes files ($GIT_DIR/info/attributes, the .gitattributes file at the top level of the working tree, or the global or system-wide gitattributes files), not in .gitattributes files in working tree subdirectories. The built-in macro attribute "binary" is equivalent to:
[attr]binary -diff -merge -text
NOTES Git does not follow symbolic links when accessing a .gitattributes file in the working tree. This keeps behavior consistent when the file is accessed from the index or a tree versus from the filesystem.
EXAMPLES If you have these three gitattributes file:
(in $GIT_DIR/info/attributes)
a* foo !bar -baz
(in .gitattributes) abc foo bar baz
(in t/.gitattributes) ab* merge=filfre abc -foo -bar *.c frotz
the attributes given to path t/abc are computed as follows:
1. By examining t/.gitattributes (which is in the same directory as the path in question), Git finds that the first line matches. merge attribute is set. It also finds that the second line matches, and attributes foo and bar are unset.
2. Then it examines .gitattributes (which is in the parent directory), and finds that the first line matches, but t/.gitattributes file already decided how merge, foo and bar attributes should be given to this path, so it leaves foo and bar unset. Attribute baz is set.
3. Finally it examines $GIT_DIR/info/attributes. This file is used to override the in-tree settings. The first line is a match, and foo is set, bar is reverted to unspecified state, and baz is unset.
As the result, the attributes assignment to t/abc becomes:
foo set to true bar unspecified baz set to false merge set to string value "filfre" frotz unspecified
SEE ALSO git-check-attr(1).
GIT Part of the git(1) suite
Git 2.47.1 11/25/2024 GITATTRIBUTES(5)
Git LFS Tracking
Once you have installed the Git LFS client,
and configured a git repository to use Git LFS,
run the git lfs track
command to
specify the filename patterns that Git LFS should manage.
This information is stored in files called .gitattributes
,
which should be committed to git.
You can assign additional file name patterns to LFS anytime.
Try To Avoid Migrating Files From Git To Gif LFS
You will have less work and fewer problems if you set up Git LFS tracking before you commit any files that will later need to be migrated to Git LFS.Git-lfs-track Man Page
GIT-LFS-TRACK(1) GIT-LFS-TRACK(1)
NAME git-lfs-track - View or add Git LFS paths to Git attributes
SYNOPSIS git lfs track [options] [<pattern>...]
DESCRIPTION Start tracking the given patterns(s) through Git LFS. The argument is written to .gitattributes. If no paths are provided, simply list the currently-tracked paths.
The gitattributes documentation <https://git-scm.com/docs/gitattributes> states that patterns use the gitignore pattern rules <https://git-scm.com/docs/gitignore> to match paths. This means that patterns which contain asterisk (*), question mark (?), and the bracket characters ([ and ]) are treated specially; to disable this behavior and treat them literally instead, use --filename or escape the character with a backslash.
OPTIONS --verbose, -v If enabled, have git lfs track log files which it will touch. Disabled by default.
--dry-run, -d If enabled, have git lfs track log all actions it would normally take (adding entries to .gitattributes, touching files on disk, etc) without performing any mutative operations to the disk.
git lfs track --dry-run [files] also implicitly mocks the behavior of passing the --verbose, and will log in greater detail what it is doing.
Disabled by default.
--filename Treat the arguments as literal filenames, not as patterns. Any special glob characters in the filename will be escaped when writing the .gitattributes file.
--lockable, -l Make the paths 'lockable', meaning they should be locked to edit them, and will be made read-only in the working copy when not locked.
--not-lockable Remove the lockable flag from the paths so they are no longer read-only unless locked.
--no-excluded Do not list patterns that are excluded in the output; only list patterns that are tracked. --no-modify-attrs: Makes matched entries stat-dirty so that Git can re-index files you wish to convert to LFS. Does not modify any .gitattributes file(s).
EXAMPLES • List the patterns that Git LFS is currently tracking:
git lfs track
• Configure Git LFS to track GIF files:
git lfs track "*.gif"
• Configure Git LFS to track PSD files and make them read-only unless locked:
git lfs track --lockable "*.psd"
• Configure Git LFS to track the file named project [1].psd:
git lfs track --filename "project [1].psd"
SEE ALSO git-lfs-untrack(1), git-lfs-install(1), gitattributes(5), gitignore(5).
Part of the git-lfs(1) suite.
GIT-LFS-TRACK(1)
Using git-lfs-track
Before running git lfs track
,
use git ls-files
to
ensure no files matching the file name patterns you wish to track have already been committed.
The Git LFS FAQ
discusses what happens if you run afoul of this caveat.
I raised an issue asking for clarification.
Here is an example that shows how to ensure that it is safe to track a file name pattern.
Before I attempted to have Git LFS track all mp4
files, I run the following incantation:
TODO: Does this (?i)
actually work?
$ git ls-files '(?i)*.mp4'
This will break the repository for everyone else. The continuity of your employment may be at stake.
Please read the section below entitled Converting An Existing Repository to LFS
$ git init "$work/blah" # Create an empty git repository
$ cd "$work/blah"
$ git lfs install
$ git config -f .lfsconfig lfs.url \ http://my_lfs_server/api/my_org/my_repo
$ git ls-files git ls-files video1.mp4 # Of course nothing is listed because there are no files yet
$ git lfs track --filename video1.mp4 Tracking "video1.mp4"
$ # Now add files to this git repo, commit and push as usual
git lfs track
creates a file called .gitattributes
in the current directory.
Unless you actually want multiple .gitattributes
files,
be sure to always run the command from the root of the git repository.
$ cat .gitattributes video1.mp4 filter=lfs diff=lfs merge=lfs -text
.gitattributes
does not need to be committed to the repository to work,
it just needs to be present.
However, you should commit it, so every copy of the repository works the same.
Once the wildcard specification has been added to .gitattributes
,
just commit and push it using git lfs
:
$ git add .gitattributes
$ git commit -m "Git LFS is now tracking mp4s"
$ git push -u origin master
Now let’s use git lfs track
to specify that all files with an mp4
extension should be managed by LFS.
Remember that wildcards are case-sensitive, so "*.mp4" is not the same as "*.MP4"!
The following shows how the (?i)
flag specifies a case-insensitive pattern.
TODO: Does this (?i)
actually work?
$ git ls-files "(?i)*.mp4"
$ git lfs track "(?i)*.mp4" Tracking "(?i)*.mp4"
$ git add .gitattributes
$ git commit -m "Store all MP4s in LFS"
$ git push
Now just commit and push large files as you normally would.
$ git add blah.mp4
$ git commit -m "Just another video"
$ git push Uploading LFS objects: 100% (2/2), 25 MB | 0 B/s, done.
Converting An Existing Repository to LFS
For repositories that already have files that match at least one LFS wildcard pattern,
the git lfs migrate import
command should be used after enabling tracking.
As the name of the command suggests, it migrates existing repository files into Git LFS.
Here is the man page for git-lfs-migrate
:
GIT-LFS-MIGRATE(1) GIT-LFS-MIGRATE(1)
NAME git-lfs-migrate - Migrate history to or from Git LFS
SYNOPSIS git lfs migrate <mode> [options] [--] [branch ...]
DESCRIPTION Convert files in a Git repository to or from Git LFS pointers, or summarize Git file sizes by file type. The import mode converts Git files (i.e., blobs) to Git LFS, while the export mode does the reverse, and the info mode provides an informational summary which may be useful in deciding which files to import or export.
In all modes, by default git lfs migrate operates only on the currently checked-out branch, and only on files (of any size and type) added in commits which do not exist on any remote. Multiple options are available to override these defaults.
When converting files to or from Git LFS, the git lfs migrate command will only make changes to your local repository and working copy, never any remotes. This is intentional as the import and export modes are generally "destructive" in the sense that they rewrite your Git history, changing commits and generating new commit SHAs. (The exception is the "no-rewrite" import sub-mode; see IMPORT WITHOUT REWRITING HISTORY for details.)
You should therefore always first commit or stash any uncommitted work before using the import or export modes, and then validate the result of the migration before pushing the changes to your remotes, for instance by running the info mode and by examining your rewritten commit history.
Once you are satisfied with the changes, you will need to force-push the new Git history of any rewritten branches to all your remotes. This is a step which should be taken with care, since you will be altering the Git history on your remotes.
To examine or modify files in branches other than the currently checked-out one, branch refs may be specified directly, or provided in one or more --include-ref options. They may also be excluded by prefixing them with ^ or providing them in --exclude-ref options. Use the --everything option to specify that all refs should be examined, including all remote refs. See INCLUDE AND EXCLUDE REFERENCES for details.
For the info and import modes, all file types are considered by default; while useful in the info mode, this is often not desirable when importing, so either filename patterns (pathspecs) or the --fixup option should normally be specified in that case. (At least one include pathspec is required for the export mode.) Pathspecs may be defined using the --include and --exclude options (-I and -X for short), as described in INCLUDE AND EXCLUDE.
As typical Git LFS usage depends on tracking specific file types using filename patterns defined in .gitattributes files, the git lfs migrate command will examine, create, and modify .gitattributes files as necessary. The .gitattributes files will always be assigned the default read/write permissions mode (i.e., without execute permissions). Any symbolic links with that name will cause the migration to halt prematurely.
The import mode (see IMPORT) will convert Git objects of the file types specified (e.g., with --include) to Git LFS pointers, and will add entries for those file types to .gitattributes files, creating those files if they do not exist. The result should be as if git lfs track commands had been run at the points in your Git history corresponding to where each type of converted file first appears. The exception is if the --fixup option is given, in which case the import mode will only examine any existing .gitattributes files and then convert Git objects which should be tracked by Git LFS but are not yet.
The export mode (see EXPORT) works as the reverse operation to the import mode, converting any Git LFS pointers that match the file types specified with --include, which must be given at least once. Note that .gitattributes entries will not be removed, nor will the files; instead, the export mode inserts "do not track" entries similar to those created by the git lfs untrack command. The --remote option is available in the export mode to specify the remote from which Git LFS objects should be fetched if they do not exist in the local Git LFS object cache; if not provided, origin is used by default.
The info mode (see INFO) summarizes by file type (i.e., by filename extension) the total number and size of files in a repository. Note that like the other two modes, by default the info mode operates only on the currently checked-out branch and only on commits which do not exist on any remote, so to get a summary of the entire repository across all branches, use the --everything option. If objects have already been converted to Git LFS pointers, then by default the size of the referenced objects is totaled and reported separately. You may also choose to ignore them by using --pointers=ignore or to treat the pointers as files by using --pointers=no-follow. (The latter option is akin to how existing Git LFS pointers were handled by the info mode in prior versions of Git LFS).
When using the --everything option, take note that it means all commits reachable from all refs (local and remote) will be considered, but not necessarily all file types. The import and info modes consider all file types by default, although the --include and --exclude options constrain this behavior.
While the --everything option means all commits reachable from any ref will be considered for migration, after migration only local refs will be updated even when --everything is specified. This ensures remote refs stay synchronized with their remote. In other words, refs/heads/foo will be updated with the --everything option, but refs/remotes/origin/foo will not, so it stays in sync with the remote until git push origin foo is performed. After checking that the results of a migration with --everything are satisfactory, it may be convenient to push all local branches to your remotes by using the --all option to git push.
Unless the --skip-fetch option is given, git lfs migrate always begins by fetching updated lists of refs from all the remotes returned by git remote, but as noted above, after making changes to your local Git history while converting objects, it will never automatically push those changes to your remotes.
MODES info Show information about repository size. See INFO.
import Convert Git objects to Git LFS pointers. See IMPORT and IMPORT WITHOUT REWRITING HISTORY
export Convert Git LFS pointers to Git objects. See EXPORT.
OPTIONS -I <paths>, --include=<paths> See INCLUDE AND EXCLUDE.
-X <paths>, --exclude=<paths> See INCLUDE AND EXCLUDE.
--include-ref=<refname> See INCLUDE AND EXCLUDE REFERENCES.
--include-ref=<refname> See INCLUDE AND EXCLUDE REFERENCES.
--exclude-ref=<refname> See INCLUDE AND EXCLUDE REFERENCES.
--skip-fetch Assumes that the known set of remote references is complete, and should not be refreshed when determining the set of "un-pushed" commits to migrate. Has no effect when combined with --include-ref or --exclude-ref.
--everything See INCLUDE AND EXCLUDE REFERENCES.
Note: Git refs are "case-sensitive" on all platforms in "packed from" (see git-pack-refs(1)). On "case-insensitive" file systems, e.g. NTFS on Windows or default APFS on macOS, git-lfs-migrate(1) would only migrate the first ref if two or more refs are equal except for upper/lower case letters.
--yes Assume a yes answer to any prompts, permitting noninteractive use. Currently, the only such prompt is the one asking whether to overwrite (destroy) any working copy changes. Thus, specifying this option may cause data loss if you are not careful.
[branch ...] Migrate only the set of branches listed. If not given, git-lfs-migrate(1) will migrate the currently checked out branch.
References beginning with ^ will be excluded, whereas branches that do not begin with ^ will be included.
If any of --include-ref or --exclude-ref are given, the checked out branch will not be appended, but branches given explicitly will be appended.
INFO The info mode summarizes the sizes of file objects present in the Git history. It supports all the core migrate options and these additional ones:
--above=<size> Only count files whose individual filesize is above the given size. size may be specified as a number of bytes, or a number followed by a storage unit, e.g., "1b", "20 MB", "3 TiB", etc.
If a set of files sharing a common extension has no files in that set whose individual size is above the given --above no files no entry for that set will be shown.
--top=<n> Only display the top n entries, ordered by how many total files match the given pathspec. The default is to show only the top 5 entries. When existing Git LFS objects are found, an extra, separate "LFS Objects" line is output in addition to the top n entries, unless the --pointers option is used to change this behavior.
--unit=<unit> Format the number of bytes in each entry as a quantity of the storage unit provided. Valid units include: * b, kib, mib, gib, tib, pib - for IEC storage units * b, kb, mb, gb, tb, pb - for SI storage units
If a --unit is not specified, the largest unit that can fit the number of counted bytes as a whole number quantity is chosen.
--pointers=[follow|no-follow|ignore] Treat existing Git LFS pointers in the history according to one of three alternatives. In the default follow case, if any pointers are found, an additional separate "LFS Objects" line item is output which summarizes the total number and size of the Git LFS objects referenced by pointers. In the ignore case, any pointers are simply ignored, while the no-follow case replicates the behavior of the info mode in older Git LFS versions and treats any pointers it finds as if they were regular files, so the output totals only include the contents of the pointers, not the contents of the objects to which they refer.
--fixup Infer --include and --exclude filters on a per-commit basis based on the .gitattributes files in a repository. In practice, this option counts any filepaths which should be tracked by Git LFS according to the repository’s .gitattributes file(s), but aren’t already pointers. The .gitattributes files are not reported, in contrast to the normal output of the info mode. This option is incompatible with explicitly given --include, --exclude filters and with any --pointers setting other than ignore, hence --fixup implies --pointers=ignore if it is not explicitly set.
The format of the output shows the filename pattern, the total size of the file objects (excluding those below the --above threshold, if one was defined), and the ratio of the number of files above the threshold to the total number of files; this ratio is also shown as a percentage. For example:
*.gif 93 MB 9480/10504 files(s) 90% *.png 14 MB 1732/1877 files(s) 92%
By default only the top five entries are shown, but --top allows for more or fewer to be output as desired.
IMPORT The import mode migrates objects present in the Git history to pointer files tracked and stored with Git LFS. It supports all the core migrate options and these additional ones:
--verbose Print the commit oid and filename of migrated files to STDOUT.
--above=<size> Only migrate files whose individual filesize is above the given size. size may be specified as a number of bytes, or a number followed by a storage unit, e.g., "1b", "20 MB", "3 TiB", etc. This option cannot be used with the --include, --exclude, and --fixup options.
--object-map=<path> Write to path a file with the mapping of each rewritten commits. The file format is CSV with this pattern: OLD-SHA,NEW-SHA
--no-rewrite Migrate objects to Git LFS in a new commit without rewriting Git history. Please note that when this option is used, the migrate import command will expect a different argument list, specialized options will become available, and the core migrate options will be ignored. See IMPORT WITHOUT REWRITING HISTORY.
--fixup Infer --include and --exclude filters on a per-commit basis based on the .gitattributes files in a repository. In practice, this option imports any filepaths which should be tracked by Git LFS according to the repository’s .gitattributes file(s), but aren’t already pointers. This option is incompatible with explicitly given --include, --exclude filters.
If --no-rewrite is not provided and --include or --exclude (-I, -X, respectively) are given, the .gitattributes will be modified to include any new filepath patterns as given by those flags.
If --no-rewrite is not provided and neither of those flags are given, the gitattributes will be incrementally modified to include new filepath extensions as they are rewritten in history.
IMPORT WITHOUT REWRITING HISTORY The import mode has a special sub-mode enabled by the --no-rewrite flag. This sub-mode will migrate objects to pointers as in the base import mode, but will do so in a new commit without rewriting Git history. When using this sub-mode, the base migrate options, such as --include-ref, will be ignored, as will those for the base import mode. The migrate command will also take a different argument list. As a result of these changes, --no-rewrite will only operate on the current branch - any other interested branches must have the generated commit merged in.
The --no-rewrite sub-mode supports the following options and arguments:
-m <message>, --message=<message> Specifies a commit message for the newly created commit.
[file ...] The list of files to import. These files must be tracked by patterns specified in the gitattributes.
If --message is given, the new commit will be created with the provided message. If no message is given, a commit message will be generated based on the file arguments.
EXPORT The export mode migrates Git LFS pointer files present in the Git history out of Git LFS, converting them into their corresponding object files. It supports all the core migrate options and these additional ones:
--verbose Print the commit oid and filename of migrated files to STDOUT.
--object-map=<path> Write to path a file with the mapping of each rewritten commit. The file format is CSV with this pattern: OLD-SHA,NEW-SHA
--remote=<git-remote> Download LFS objects from the provided git-remote during the export. If not provided, defaults to origin.
The export mode requires at minimum a pattern provided with the --include argument to specify which files to export. Files matching the --include patterns will be removed from Git LFS, while files matching the --exclude patterns will retain their Git LFS status. The export command will modify the .gitattributes to set/unset any filepath patterns as given by those flags.
INCLUDE AND EXCLUDE You can specify that git lfs migrate should only convert files whose pathspec matches the --include glob patterns and does not match the --exclude glob patterns, either to reduce total migration time or to only migrate part of your repo. Multiple patterns may be given using commas as delimiters.
Pattern matching is done so as to be functionally equivalent to the pattern matching format of .gitattributes. In addition to simple file extension matches (e.g., .gif) patterns may also specify directory paths, in which case the path/* format may be used to match recursively.
Note that this form of pattern matching for the --include and --exclude options used by the git lfs migrate command is unique among the suite of git lfs commands. Other commands which also take these options, such as git lfs ls-files, use the gitignore(5) form of pattern matching instead.
INCLUDE AND EXCLUDE REFERENCES You can specify that git lfs migrate should only convert files added in commits reachable from certain references, namely those defined using one or more --include-ref options, and should ignore files in commits reachable from references defined in --exclude-ref options.
D---E---F / \ A---B------C refs/heads/my-feature \ \ \ refs/heads/main \ refs/remotes/origin/main
In the above configuration, the following commits are reachable by each ref:
refs/heads/main: C, B, A refs/heads/my-feature: F, E, D, B, A refs/remote/origin/main: A
The following git lfs migrate options would, therefore, include commits F, E, D, C, and B, but exclude commit A:
--include-ref=refs/heads/my-feature --include-ref=refs/heads/main --exclude-ref=refs/remotes/origin/main
The presence of flag --everything indicates that all commits reachable from all local and remote references should be migrated (but note that the remote refs themselves will not be updated).
EXAMPLES Migrate unpushed commits A common use case for the migrate command is to convert large Git objects to LFS before pushing your commits. By default, it only scans commits that don’t exist on any remote, so long as the repository is non-bare.
First, run git lfs migrate info to list the file types taking up the most space in your repository:
$ git lfs migrate info migrate: Fetching remote refs: ..., done migrate: Sorting commits: ..., done migrate: Examining commits: 100% (1/1), done *.mp3 284 MB 1/1 files(s) 100% *.pdf 42 MB 8/8 files(s) 100% *.psd 9.8 MB 15/15 files(s) 100% *.ipynb 6.9 MB 6/6 files(s) 100% *.csv 5.8 MB 2/2 files(s) 100%
Now, you can run git lfs migrate import to convert some file types to LFS:
$ git lfs migrate import --include="*.mp3,*.psd" migrate: Fetching remote refs: ..., done migrate: Sorting commits: ..., done migrate: Rewriting commits: 100% (1/1), done main d2b959babd099fe70da1c1512e2475e8a24de163 -> 136e706bf1ae79643915c134e17a6c933fd53c61 migrate: Updating refs: ..., done
If after conversion you find that some files in your working directory have been replaced with Git LFS pointers, this is normal, and the working copies of these files can be repopulated with their full expected contents by using git lfs checkout.
Migrate local history You can also migrate the entire history of your repository:
# Check for large files and existing Git LFS objects in your local main branch $ git lfs migrate info --include-ref=main
# Check for large files and existing Git LFS objects in every branch $ git lfs migrate info --everything
# Check for large files in every branch, ignoring any existing Git LFS objects, # and listing the top 100 or fewer results $ git lfs migrate info --everything --pointers=ignore --top=100
The same flags will work in import mode:
# Convert all zip files in your main branch $ git lfs migrate import --include-ref=main --include="*.zip"
# Convert all zip files in every local branch $ git lfs migrate import --everything --include="*.zip"
# Convert all files over 100K in every local branch $ git lfs migrate import --everything --above=100Kb
Note: This will require a force-push to any existing Git remotes. Using the --all option when force-pushing may be convenient if many local refs were updated, e.g., after importing to Git LFS with the --everything option.
Migrate without rewriting local history You can also migrate files without modifying the existing history of your repository. Note that in the examples below, files in subdirectories are not included because they are not explicitly specified.
Without a specified commit message:
$ git lfs migrate import --no-rewrite test.zip *.mp3 *.psd
With a specified commit message:
$ git lfs migrate import --no-rewrite \ -m "Import test.zip, .mp3, .psd files in root of repo" \ test.zip *.mp3 *.psd
Migrate from Git LFS If you no longer wish to use Git LFS for some or all of your files, you can use the export mode to convert Git LFS objects into regular Git blobs again.
The export mode requires at least one --include pathspec, and will download any objects not found locally from your origin Git remote, or from the Git remote you specify with the --remote option.
# Convert all zip Git LFS objects to files in your main branch $ git lfs migrate export --include-ref=main --include="*.zip"
# Convert all zip Git LFS objects to files in every local branch, # fetching any object data not cached locally from the my-remote Git remote $ git lfs migrate export --everything --include="*.zip" --remote=my-remote
# Convert all Git LFS objects to files in every local branch $ git lfs migrate export --everything --include="*"
Note: This will require a force-push to any existing Git remotes. Using the --all option when force-pushing may be convenient if many local refs were updated, e.g., after exporting from Git LFS with the --everything option.
SEE ALSO git-lfs-checkout(1), git-lfs-ls-files(1), git-lfs-track(1), git-lfs-untrack(1), gitattributes(5), gitignore(5).
Part of the git-lfs(1) suite.
GIT-LFS-MIGRATE(1)
The git-lfs-migrate
command rewrites the entire git history to replace committed files
with pointers managed by LFS.
Only committed files whose names match a pattern stored in .lfsconfig
are affected.
Is this true?
Because this command modifies the git history,
git push --force
will be required to update remote repositories.
Here is an example sequence:
$ # BACK UP YOUR GIT REPOSITORY BEFORE MESSING WITH IT
$ git pull # This repo is now up-to-date
$ git lfs install
$ git ls-files '*.mp4' '*.MP4' video1.mp4 video2.mp4
$ git lfs track '*.mp4' '*.MP4' Tracking "*.mp4" Tracking "*.MP4"
$ git lfs migrate import --include="*.mp4,*.MP4" --everything
$ git push --force # All work done by others since the git pull above is lost
This breaks the repository for everyone else! They will have to re-clone it, and when they do, they will have lost all the work they did since they were last able to push.
If you find yourself in this unfortunate situation, I have provided a recovery script Recovering From Data Loss After Git LFS Import
You can use git lfs ls-files
to confirm that Git LFS is managing your mp4
files.
An asterisk (*) after the OID indicates a full object,
while a minus (-) indicates an LFS pointer.
$ git lfs ls-files 3c2f7aedfb - blah.mp4
If the output contains an asterisk, like 3c2f7aedfb * blah.mp4
,
then mp4
s are not managed by Git LFS and you need to figure out why.
GIT-LFS-LS-FILES(1) GIT-LFS-LS-FILES(1)
NAME git-lfs-ls-files - Show information about Git LFS files in the index and working tree
SYNOPSIS git lfs ls-files [<ref>] git lfs ls-files <ref> <ref>
DESCRIPTION Display paths of Git LFS files that are found in the tree at the given reference. If no reference is given, scan the currently checked-out branch. If two references are given, the LFS files that are modified between the two references are shown; deletions are not listed.
An asterisk (*) after the OID indicates a full object, a minus (-) indicates an LFS pointer.
OPTIONS -l, --long Show the entire 64 character OID, instead of just first 10.
-s, --size Show the size of the LFS object between parenthesis at the end of a line.
-d, --debug Show as much information as possible about a LFS file. This is intended for manual inspection; the exact format may change at any time.
-a, --all Inspects the full history of the repository, not the current HEAD (or other provided reference). This will include previous versions of LFS objects that are no longer found in the current tree.
--deleted Shows the full history of the given reference, including objects that have been deleted.
-I <paths>, --include=<paths> Include paths matching only these patterns; see [_fetch_settings].
-X <paths>, --exclude=<paths> Exclude paths matching any of these patterns; see [_fetch_settings].
-n, --name-only Show only the lfs tracked file names.
SEE ALSO git-lfs-status(1), git-lfs-config(5).
Part of the git-lfs(1) suite.
GIT-LFS-LS-FILES(1)
Now move to another computer with Git LFS installed and clone the repo. Ensure the large files are downloaded:
$ cd $work
$ git clone http://git_server/my_org/my_repo.git
$ git lfs fetch --all
$ git lfs ls-files 3c2f7aedfb - blah.mp4
Now that you know the large files have been provided by the LFS server of the cloned git repository, you should verify that they are intact by testing them.
I have published 5 articles about the Git large file system (LFS). They are meant to be read in order.
- Git Large File System Overview
- Git LFS Client Installation
- Git LFS Server URLs
- Git LFS Filename Patterns & Tracking
- Git LFS Client Configuration & Commands
- Working With Git LFS
- Evaluation Procedure For Git LFS Servers
7 articles are still in process.
Instructions for typing along are given for Ubuntu and WSL/Ubuntu. If you have a Mac, most of this information should be helpful.