NAME

gitattributes - Defining attributes per path

SYNOPSIS

$GIT_DIR/info/attributes, .gitattributes

DESCRIPTION

A gitattributes file is a simple text file that givesattributes to pathnames.

Each line in gitattributes file is of form:

  1. pattern attr1 attr2 ...

That is, a pattern followed by an attributes list,separated by whitespaces. Leading and trailing whitespaces areignored. Lines that begin with # are ignored. Patternsthat begin with a double quote are quoted in C style.When the pattern matches the path in question, the attributeslisted 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 theattribute in the attribute list.

  • Unset

  • The path has the attribute with special value "false";this is specified by listing the name of the attributeprefixed 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 attributefollowed by an equal sign = and its value in theattribute list.

  • Unspecified

  • No pattern matches the path, and nothing says ifthe path has or does not have the attribute, theattribute for the path is said to be Unspecified.

When more than one pattern matches the path, a later lineoverrides an earlier line. This overriding is done perattribute.

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 pathsinside that directory (so using the trailing-slash path/ syntax ispointless in an attributes file; use path/** instead)

When deciding what attributes are assigned to a path, Gitconsults $GIT_DIR/info/attributes file (which has the highestprecedence), .gitattributes file in the same directory as thepath in question, and its parent directories up to the toplevel of thework tree (the further the directory that contains .gitattributesis from the path in question, the lower its precedence). Finallyglobal and system-wide files are considered (they have the lowestprecedence).

When the .gitattributes file is missing from the work tree, thepath in the index is used as a fall-back. During checkout process,.gitattributes in the index is used and then the file in theworking tree is used as a fall-back.

If you wish to affect only a single repository (i.e., to assignattributes to files that are particular toone user’s workflow for that repository), thenattributes should be placed in the $GIT_DIR/info/attributes file.Attributes which should be version-controlled and distributed to otherrepositories (i.e., attributes of interest to all users) should go into.gitattributes files. Attributes that should affect all repositoriesfor a single user should be placed in a file specified by thecore.attributesFile configuration option (see git-config[1]).Its default value is $XDG_CONFIG_HOME/git/attributes. If $XDG_CONFIG_HOMEis 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 attributefor a path to Unspecified state. This can be done by listingthe name of the attribute prefixed with an exclamation point !.

EFFECTS

Certain operations by Git can be influenced by assigningparticular attributes to a path. Currently, the followingoperations are attributes-aware.

Checking-out and checking-in

These attributes affect how the contents stored in therepository are copied to the working tree files when commandssuch as git switch, git checkout and git merge run.They also affect howGit stores the contents you prepare in the working tree in therepository upon git add and git commit.

text

This attribute enables and controls end-of-line normalization. When atext file is normalized, its line endings are converted to LF in therepository. To control what line ending style is used in the workingdirectory, use the eol attribute for a single file and thecore.eol configuration variable for all text files.Note that setting core.autocrlf to true or input overridescore.eol (see the definitions of those options ingit-config[1]).

  • Set
  • Setting the text attribute on a path enables end-of-linenormalization and marks the path as a text file. End-of-lineconversion takes place without guessing the content type.

  • Unset

  • Unsetting the text attribute on a path tells Git not toattempt any end-of-line conversion upon checkin or checkout.

  • Set to string value "auto"

  • When text is set to "auto", the path is marked for automaticend-of-line conversion. If Git decides that the content istext, its line endings are converted to LF on checkin.When the file has been committed with CRLF, no conversion is done.

  • Unspecified

  • If the text attribute is unspecified, Git uses thecore.autocrlf configuration variable to determine if thefile should be converted.

Any other value causes Git to act as if text has been leftunspecified.

eol

This attribute sets a specific line-ending style to be used in theworking directory. It enables end-of-line conversion without anycontent checks, effectively setting the text attribute. Note thatsetting this attribute on paths which are in the index with CRLF lineendings may make the paths to be considered dirty. Adding the path tothe index again will normalize the line endings in the index.

  • Set to string value "crlf"
  • This setting forces Git to normalize line endings for thisfile on checkin and convert them to CRLF when the file ischecked out.

  • Set to string value "lf"

  • This setting forces Git to normalize line endings to LF oncheckin and prevents conversion to CRLF when the file ischecked out.

Backwards compatibility with crlf attribute

For backwards compatibility, the crlf attribute is interpreted asfollows:

  1. crlf text
  2. -crlf -text
  3. crlf=input eol=lf

End-of-line conversion

While Git normally leaves file contents alone, it can be configured tonormalize line endings to LF in the repository and, optionally, toconvert them to CRLF when files are checked out.

If you simply want to have CRLF line endings in your working directoryregardless of the repository you are working with, you can set theconfig variable "core.autocrlf" without using any attributes.

  1. [core]
  2. autocrlf = true

This does not force normalization of text files, but does ensurethat text files that you introduce to the repository have their lineendings normalized to LF when they are added, and that files that arealready normalized in the repository stay normalized.

If you want to ensure that text files that any contributor introduces tothe repository have their line endings normalized, you can set thetext attribute to "auto" for all files.

  1. * text=auto

The attributes allow a fine-grained control, how the line endingsare converted.Here is an example that will make Git normalize .txt, .vcproj and .shfiles, ensure that .vcproj files have CRLF and .sh files have LF inthe working directory, and prevent .jpg files from being normalizedregardless of their content.

  1. * text=auto
  2. *.txt text
  3. *.vcproj text eol=crlf
  4. *.sh text eol=lf
  5. *.jpg -text
NoteWhen text=auto conversion is enabled in a cross-platformproject using push and pull to a central repository the text filescontaining CRLFs should be normalized.

From a clean working directory:

  1. $ echo "* text=auto" >.gitattributes
  2. $ git add --renormalize .
  3. $ git status # Show files that will be normalized
  4. $ 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.

  1. manual.pdf -text

Conversely, text files that Git does not detect can have normalizationenabled manually.

  1. weirdchars.txt text

If core.safecrlf is set to "true" or "warn", Git verifies ifthe conversion is reversible for the current setting ofcore.autocrlf. For "true", Git rejects irreversibleconversions; for "warn", Git only prints a warning but acceptsan irreversible conversion. The safety triggers to prevent sucha conversion done to the files in the work tree, but there are afew exceptions. Even though…​

  • git add itself does not touch the files in the work tree, thenext checkout would, so the safety triggers;

  • git apply to update a text file with a patch does touch the filesin the work tree, but the operation is about text files and CRLFconversion is about fixing the line ending inconsistencies, so thesafety does not trigger;

  • git diff itself does not touch the files in the work tree, it isoften run to inspect the changes you intend to next git add. Tocatch 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 otherencodings (e.g. UTF-16) are interpreted as binary and consequentlybuilt-in Git text processing tools (e.g. git diff) as well as most Gitweb 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 workingdirectory with the working-tree-encoding attribute. If a file with thisattribute is added to Git, then Git reencodes the content from thespecified encoding to UTF-8. Finally, Git stores the UTF-8 encodedcontent in its internal data structure (called "the index"). On checkoutthe content is reencoded back to the specified encoding.

Please note that using the working-tree-encoding attribute may have anumber of pitfalls:

  • Alternative Git implementations (e.g. JGit or libgit2) and older Gitversions (as of March 2018) do not support the working-tree-encodingattribute. If you decide to use the working-tree-encoding attributein your repository, then it is strongly recommended to ensure that allclients working with the repository support it.

For example, Microsoft Visual Studio resources files (.rc) orPowerShell script files (.ps1) are sometimes encoded in UTF-16.If you declare *.ps1 as files as UTF-16 and you add foo.ps1 witha working-tree-encoding enabled Git client, then foo.ps1 will bestored as UTF-8 internally. A client without working-tree-encodingsupport will checkout foo.ps1 as UTF-8 encoded file. This willtypically cause trouble for the users of this file.

If a Git client that does not support the working-tree-encodingattribute adds a new file bar.ps1, then bar.ps1 will bestored "as-is" internally (in this example probably as UTF-16).A client with working-tree-encoding support will interpret theinternal 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 theconversion might not be UTF-8 round trip safe. If you suspect yourencoding to not be round trip safe, then add it tocore.checkRoundtripEncoding to make Git check the round tripencoding (see git-config[1]). SHIFT-JIS (Japanese characterset) is known to have round trip issues with UTF-8 and is checked bydefault.

  • Reencoding content requires resources that might slow down certainGit operations (e.g git checkout or git add).

Use the working-tree-encoding attribute only if you cannot store a filein UTF-8 encoding and if you want Git to be able to process the contentas text.

As an example, use the following attributes if your *.ps1 files areUTF-16 encoded with byte order mark (BOM) and you want Git to performautomatic line ending conversion based on your platform.

  1. *.ps1 text working-tree-encoding=UTF-16

Use the following attributes if your *.ps1 files are UTF-16 littleendian encoded without BOM and you want Git to use Windows line endingsin the working directory (use UTF-16LE-BOM instead of UTF-16LE ifyou want UTF-16 little endian with BOM).Please note, it is highly recommended toexplicitly define the line endings with eol if the working-tree-encodingattribute is used to avoid ambiguity.

  1. *.ps1 text working-tree-encoding=UTF-16LE eol=CRLF

You can get a list of all available encodings on your platform with thefollowing command:

  1. iconv --list

If you do not know the encoding of a file, then you can use the filecommand to guess the encoding:

  1. file foo.ps1

ident

When the attribute ident is set for a path, Git replaces$Id$ in the blob object with $Id:, followed by the40-character hexadecimal blob object name, followed by a dollarsign $ upon checkout. Any byte sequence that begins with$Id: and ends with $ in the worktree file is replacedwith $Id$ upon check-in.

filter

A filter attribute can be set to a string value that names afilter driver specified in the configuration.

A filter driver consists of a clean command and a smudgecommand, either of which can be left unspecified. Uponcheckout, when the smudge command is specified, the command isfed the blob object from its standard input, and its standardoutput is used to update the worktree file. Similarly, theclean command is used to convert the contents of worktree fileupon checkin. By default these commands process only a singleblob and terminate. If a long running process filter is usedin place of clean and/or smudge filters, then Git can processall blobs with a single filter command invocation for the entirelife of a single Git command, for example git add —all. If along running process filter is configured then it always takesprecedence over a configured single blob filter. See sectionbelow for the description of the protocol used to communicate witha process filter.

One use of the content filtering is to massage the content into a shapethat is more convenient for the platform, filesystem, and the user to use.For this mode of operation, the key phrase here is "more convenient" andnot "turning something unusable into usable". In other words, the intentis that if someone unsets the filter driver definition, or does not havethe appropriate filter program, the project should still be usable.

Another use of the content filtering is to store the content that cannotbe directly used in the repository (e.g. a UUID that refers to the truecontent stored outside Git, or an encrypted content) and turn it into ausable form upon checkout (e.g. download the external content, or decryptthe encrypted content).

These two filters behave differently, and by default, a filter is taken asthe former, massaging the contents into more convenient shape. A missingfilter driver definition in the config, or a filter driver that exits witha 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 unusableinto a usable content by setting the filter.<driver>.required configurationvariable 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 filterattribute for paths.

  1. *.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 tomodify the contents of C programs when the source files are checkedin ("clean" is run) and checked out (no change is made because thecommand is "cat").

  1. [filter "indent"]
  2. clean = indent
  3. smudge = cat

For best results, clean should not alter its output further if it isrun twice ("clean→clean" should be equivalent to "clean"), andmultiple smudge commands should not alter clean's output("smudge→smudge→clean" should be equivalent to "clean"). See thesection on merging below.

The "indent" filter is well-behaved in this regard: it will not modifyinput that is already correctly indented. In this case, the lack of asmudge filter means that the clean filter must accept its own outputwithout 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:

  1. [filter "crypt"]
  2. clean = openssl enc ...
  3. smudge = openssl enc -d ...
  4. required

Sequence "%f" on the filter command line is replaced with the name ofthe file the filter is working on. A filter might use this in keywordsubstitution. For example:

  1. [filter "p4"]
  2. clean = git-p4-filter --clean %f
  3. smudge = git-p4-filter --smudge %f

Note that "%f" is the name of the path that is being worked on. Dependingon the version that is being filtered, the corresponding file on disk maynot exist, or may have different contents. So, smudge and clean commandsshould not try to access the file on disk, but only act as filters on thecontent provided to them on standard input.

Long Running Filter Process

If the filter command (a string value) is defined viafilter.<driver>.process then Git can process all blobs with asingle filter invocation for the entire life of a single Gitcommand. 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, thewelcome message sent by Git is "git-filter-client", only version 2 issuppported, and the supported capabilities are "clean", "smudge", and"delay".

Afterwards Git sends a list of "key=value" pairs terminated witha flush packet. The list will contain at least the filter command(based on the supported capabilities) and the pathname of the fileto filter relative to the repository root. Right after the flush packetGit sends the content split in zero or more pkt-line packets and aflush packet to terminate content. Please note, that the filtermust not send any response before it received the content and thefinal flush packet. Also note that the "value" of a "key=value" paircan contain the "=" character whereas the key would never containthat character.

  1. packet: git> command=smudge
  2. packet: git> pathname=path/testfile.dat
  3. packet: git> 0000
  4. packet: git> CONTENT
  5. packet: git> 0000

The filter is expected to respond with a list of "key=value" pairsterminated with a flush packet. If the filter does not experienceproblems then the list must contain a "success" status. Right afterthese packets the filter is expected to send the content in zeroor more pkt-line packets and a flush packet at the end. Finally, asecond list of "key=value" pairs terminated with a flush packetis expected. The filter can change the status in the second listor keep the status as is with an empty list. Please note that theempty list must be terminated with a flush packet regardless.

  1. packet: git< status=success
  2. packet: git< 0000
  3. packet: git< SMUDGED_CONTENT
  4. packet: git< 0000
  5. packet: git< 0000 # empty list, keep "status=success" unchanged!

If the result content is empty then the filter is expected to respondwith a "success" status and a flush packet to signal the empty content.

  1. packet: git< status=success
  2. packet: git< 0000
  3. packet: git< 0000 # empty content!
  4. 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.

  1. packet: git< status=error
  2. packet: git< 0000

If the filter experiences an error during processing, then it cansend the status "error" after the content was (partially orcompletely) sent.

  1. packet: git< status=success
  2. packet: git< 0000
  3. packet: git< HALF_WRITTEN_ERRONEOUS_CONTENT
  4. packet: git< 0000
  5. packet: git< status=error
  6. packet: git< 0000

In case the filter cannot or does not want to process the contentas well as any future content for the lifetime of the Git process,then it is expected to respond with an "abort" status at any pointin the protocol.

  1. packet: git< status=abort
  2. packet: git< 0000

Git neither stops nor restarts the filter process in case the"error"/"abort" status is set. However, Git sets its exit codeaccording to the filter.<driver>.required flag, mimicking thebehavior of the filter.<driver>.clean / filter.<driver>.smudgemechanism.

If the filter dies during the communication or does not adhere tothe protocol then Git will stop the filter process and restart itwith the next file that needs to be processed. Depending on thefilter.<driver>.required flag Git will interpret that as error.

Delay

If the filter supports the "delay" capability, then Git can send theflag "can-delay" after the filter command and pathname. This flagdenotes that the filter can delay filtering the current blob (e.g. tocompensate network latencies) by responding with no content but withthe status "delayed" and a flush packet.

  1. packet: git> command=smudge
  2. packet: git> pathname=path/testfile.dat
  3. packet: git> can-delay=1
  4. packet: git> 0000
  5. packet: git> CONTENT
  6. packet: git> 0000
  7. packet: git< status=delayed
  8. 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 thefilter is expected to return a list of pathnames representing blobsthat have been delayed earlier and are now available.The list must be terminated with a flush packet followedby a "success" status that is also terminated with a flush packet. Ifno blobs for the delayed paths are available, yet, then the filter isexpected to block the response until at least one blob becomesavailable. The filter can tell Git that it has no more delayed blobsby sending an empty list. As soon as the filter responds with an emptylist, Git stops asking. All blobs that Git has not received at thispoint are considered missing and will result in an error.

  1. packet: git> command=list_available_blobs
  2. packet: git> 0000
  3. packet: git< pathname=path/testfile.dat
  4. packet: git< pathname=path/otherfile.dat
  5. packet: git< 0000
  6. packet: git< status=success
  7. packet: git< 0000

After Git received the pathnames, it will request the correspondingblobs again. These requests contain a pathname and an empty contentsection. The filter is expected to respond with the smudged contentin the usual way as explained above.

  1. packet: git> command=smudge
  2. packet: git> pathname=path/testfile.dat
  3. packet: git> 0000
  4. packet: git> 0000 # empty content!
  5. packet: git< status=success
  6. packet: git< 0000
  7. packet: git< SMUDGED_CONTENT
  8. packet: git< 0000
  9. packet: git< 0000 # empty list, keep "status=success" unchanged!

Example

A long running filter demo implementation can be found incontrib/long-running-filter/example.pl located in the Gitcore repository. If you develop your own long running filterprocess then the GIT_TRACE_PACKET environment variables can bevery helpful for debugging (see git[1]).

Please note that you cannot use an existing filter.<driver>.cleanor filter.<driver>.smudge command with filter.<driver>.processbecause the former two use a different inter process communicationprotocol than the latter one.

Interaction between checkin/checkout attributes

In the check-in codepath, the worktree file is first convertedwith filter driver (if specified and corresponding driverdefined), then the result is processed with ident (ifspecified), and then finally with text (again, if specifiedand applicable).

In the check-out codepath, the blob content is first convertedwith 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 canonicalrepository format for that file to change, such as adding aclean/smudge filter or text/eol/ident attributes, merging anythingwhere the attribute is not in place would normally cause mergeconflicts.

To prevent these unnecessary merge conflicts, Git can be told to run avirtual check-out and check-in of all three stages of a file whenresolving a three-way merge by setting the merge.renormalizeconfiguration variable. This prevents changes caused by check-inconversion from causing spurious merge conflicts when a converted fileis 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 willautomatically resolve all filter-related conflicts. Filters that donot act in this way may cause additional merge conflicts that must beresolved manually.

Generating diff text

diff

The attribute diff affects how Git generates diffs for particularfiles. It can tell Git whether to generate a textual patch for the pathor to treat the path as a binary file. It can also affect what line isshown on the hunk header @@ -k,l +n,m @@ line, tell Git to use anexternal command to generate the diff, or ask Git to convert binaryfiles to a text format before generating the diff.

  • Set
  • A path to which the diff attribute is set is treatedas text, even when they contain byte values thatnormally never appear in text files, such as NUL.

  • Unset

  • A path to which the diff attribute is unset willgenerate Binary files differ (or a binary patch, ifbinary patches are enabled).

  • Unspecified

  • A path to which the diff attribute is unspecifiedfirst gets its contents inspected, and if it looks liketext and is smaller than core.bigFileThreshold, it is treatedas text. Otherwise it would generate Binary files differ.

  • String

  • Diff is shown using the specified diff driver. Each driver mayspecify one or more options, as described in the followingsection. The options for the diff driver "foo" are definedby the configuration variables in the "diff.foo" section of theGit config file.

Defining an external diff driver

The definition of a diff driver is done in gitconfig, notgitattributes file, so strictly speaking this manual page is awrong 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:

  1. [diff "jcdiff"]
  2. command = j-c-diff

When Git needs to show you a diff for the path with diffattribute set to jcdiff, it calls the command you specifiedwith the above configuration, i.e. j-c-diff, with 7parameters, just like GIT_EXTERNAL_DIFF program is called.See git[1] for details.

Defining a custom hunk-header

Each group of changes (called a "hunk") in the textual diff outputis prefixed with a line of the form:

  1. @@ -k,l +n,m @@ TEXT

This is called a hunk header. The "TEXT" portion is by default a linethat begins with an alphabet, an underscore or a dollar sign; thismatches what GNU diff -p output uses. This default selection howeveris not suited for some contents, and you can use a customized patternto make a selection.

First, in .gitattributes, you would assign the diff attributefor paths.

  1. *.tex diff=tex

Then, you would define a "diff.tex.xfuncname" configuration tospecify a regular expression that matches a line that you wouldwant to appear as the hunk header "TEXT". Add a section to your$GIT_DIR/config file (or $HOME/.gitconfig file) like this:

  1. [diff "tex"]
  2. xfuncname = "^(\\\\(sub)*section\\{.*)$"

Note. A single level of backslashes are eaten by theconfiguration file parser, so you would need to double thebackslashes; the pattern above picks a line that begins with abackslash, and zero or more occurrences of sub followed bysection followed by open brace, to the end of line.

There are a few built-in patterns to make this easier, and texis one of them, so you do not have to write the above in yourconfiguration file (you still need to enable this with theattribute mechanism, via .gitattributes). The following built inpatterns are available:

  • ada suitable for source code in the Ada language.

  • 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.

  • 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.

  • 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.

  • tex suitable for source code for LaTeX documents.

Customizing word diff

You can customize the rules that git diff —word-diff uses tosplit words in a line, by specifying an appropriate regular expressionin the "diff.*.wordRegex" configuration variable. For example, in TeXa backslash followed by a sequence of letters forms a command, butseveral such commands can be run together without interveningwhitespace. To separate them, use a regular expression in your$GIT_DIR/config file (or $HOME/.gitconfig file) like this:

  1. [diff "tex"]
  2. wordRegex = "\\\\[a-zA-Z]+|[{}]|\\\\.|[^\\{}[:space:]]+"

A built-in pattern is provided for all languages listed in theprevious section.

Performing text diffs of binary files

Sometimes it is desirable to see the diff of a text-convertedversion of some binary files. For example, a word processordocument can be converted to an ASCII text representation, andthe diff of the text shown. Even though this conversion losessome information, the resulting diff is useful for humanviewing (but cannot be applied directly).

The textconv config option is used to define a program forperforming such a conversion. The program should take a singleargument, the name of a file to convert, and produce theresulting text on stdout.

For example, to show the diff of the exif information of afile instead of the binary information (assuming you have theexif tool installed), add the following section to your$GIT_DIR/config file (or $HOME/.gitconfig file):

  1. [diff "jpg"]
  2. textconv = exif
NoteThe text conversion is generally a one-way conversion;in this example, we lose the actual image contents and focusjust on the text data. This means that diffs generated bytextconv 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. gitformat-patch will never generate this output. If you want tosend somebody a text-converted diff of a binary file (e.g.,because it quickly conveys the changes you have made), youshould generate it separately and send it as a comment inaddition to the usual binary diff that you might send.

Because text conversion can be slow, especially when doing alarge number of them with git log -p, Git provides a mechanismto cache the output and use it in future diffs. To enablecaching, set the "cachetextconv" variable in your diff driver’sconfig. For example:

  1. [diff "jpg"]
  2. textconv = exif
  3. cachetextconv = true

This will cache the result of running "exif" on each blobindefinitely. If you change the textconv config variable for adiff driver, Git will automatically invalidate the cache entriesand re-run the textconv filter. If you want to invalidate thecache manually (e.g., because your version of "exif" was updatedand now produces better output), you can remove the cachemanually 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-formattedblobs in your repository, you can choose to use either an external diffcommand, 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 arenot bound to find line-oriented changes, nor is it necessary for theoutput to resemble unified diff. You are free to locate and reportchanges in the most appropriate way for your data format.

A textconv, by comparison, is much more limiting. You provide atransformation of the data into a line-oriented text format, and Gituses its regular diff tools to generate the output. There are severaladvantages to choosing this method:

  • Ease of use. It is often much simpler to write a binary to texttransformation than it is to perform your own diff. In many cases,existing programs can be used as textconv filters (e.g., exif,odt2txt).

  • Git diff features. By performing only the transformation stepyourself, you can still utilize many of Git’s diff features,including colorization, word-diff, and combined diffs for merges.

  • Caching. Textconv caching can speed up repeated diffs, such as thoseyou might trigger by running git log -p.

Marking files as binary

Git usually guesses correctly whether a blob contains text or binarydata by examining the beginning of the contents. However, sometimes youmay want to override its decision, either because a blob contains binarydata later in the file, or because the content, while technicallycomposed of text characters, is opaque to a human reader. For example,many postscript files contain only ASCII characters, but produce noisyand meaningless diffs.

The simplest way to mark a file as binary is to unset the diffattribute in the .gitattributes file:

  1. *.ps -diff

This will cause Git to generate Binary files differ (or a binarypatch, if binary patches are enabled) instead of a regular diff.

However, one may also want to specify other diff driver attributes. Forexample, you might want to use textconv to convert postscript files toan ASCII representation for human viewing, but otherwise treat them asbinary files. You cannot specify both -diff and diff=ps attributes.The solution is to use the diff.*.binary config option:

  1. [diff "ps"]
  2. textconv = ps2ascii
  3. binary = true

Performing a three-way merge

merge

The attribute merge affects how three versions of a file aremerged 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 thecontents in a way similar to merge command of RCSsuite. This is suitable for ordinary text files.

  • Unset

  • Take the version from the current branch as thetentative merge result, and declare that the merge hasconflicts. This is suitable for binary files that donot have a well-defined merge semantics.

  • Unspecified

  • By default, this uses the same built-in 3-way mergedriver as is the case when the merge attribute is set.However, the merge.default configuration variable can namedifferent merge driver to be used with paths for which themerge attribute is unspecified.

  • String

  • 3-way merge is performed using the specified custommerge driver. The built-in 3-way merge driver can beexplicitly specified by asking for "text" driver; thebuilt-in "take the current branch" driver can berequested with "binary".

Built-in merge drivers

There are a few built-in low-level merge drivers defined thatcan be asked for via the merge attribute.

  • text
  • Usual 3-way file level merge for text files. Conflictedregions are marked with conflict markers <<<<<<<,======= and >>>>>>>. The version from your branchappears before the ======= marker, and the versionfrom the merged branch appears after the =======marker.

  • binary

  • Keep the version from your branch in the work tree, butleave the path in the conflicted state for the user tosort out.

  • union

  • Run 3-way file level merge for text files, but takelines from both versions, instead of leaving conflictmarkers. This tends to leave the added lines in theresulting file in random order and the user shouldverify the result. Do not use this if you do notunderstand the implications.

Defining a custom merge driver

The definition of a merge driver is done in the .git/configfile, not in the gitattributes file, so strictly speaking thismanual 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:

  1. [merge "filfre"]
  2. name = feel-free merge driver
  3. driver = filfre %O %A %B %L %P
  4. recursive = binary

The merge.*.name variable gives the driver a human-readablename.

The merge.*.driver variable’s value is used to construct acommand to run to merge ancestor’s version (%O), currentversion (%A) and the other branches' version (%B). Thesethree tokens are replaced with the names of temporary files thathold the contents of these versions when the command line isbuilt. Additionally, %L will be replaced with the conflict markersize (see below).

The merge driver is expected to leave the result of the merge inthe file named with %A by overwriting it, and exit with zerostatus if it managed to merge them cleanly, or non-zero if therewere conflicts.

The merge.*.recursive variable specifies what other mergedriver to use when the merge driver is called for an internalmerge between common ancestors, when there are more than one.When left unspecified, the driver itself is used for bothinternal merge and the final merge.

The merge driver can learn the pathname in which the merged resultwill be stored via placeholder %P.

conflict-marker-size

This attribute controls the length of conflict markers left inthe work tree file during a conflicted merge. Only setting tothe value to a positive integer has any meaningful effect.

For example, this line in .gitattributes can be used to tell the mergemachinery to leave much longer (instead of the usual 7-character-long)conflict markers when merging the file Documentation/git-merge.txtresults in a conflict.

  1. Documentation/git-merge.txt conflict-marker-size=32

Checking whitespace errors

whitespace

The core.whitespace configuration variable allows you to define whatdiff and apply should consider whitespace errors for all paths inthe project (See git-config[1]). This attribute gives you finercontrol per path.

  • Set
  • Notice all types of potential whitespace errors known to Git.The tab width is taken from the value of the core.whitespaceconfiguration variable.

  • Unset

  • Do not notice anything as error.

  • Unspecified

  • Use the value of the core.whitespace configuration variable todecide what to notice as error.

  • String

  • Specify a comma separate list of common whitespace problems tonotice in the same format as the core.whitespace configurationvariable.

Creating an archive

export-ignore

Files and directories with the attribute export-ignore won’t be added toarchive files.

export-subst

If the attribute export-subst is set for a file then Git will expandseveral placeholders when adding this file to an archive. Theexpansion depends on the availability of a commit ID, i.e., ifgit-archive[1] has been given a tree instead of a commit or atag then no replacement will be done. The placeholders are the sameas 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 thecommit hash.

Packing objects

delta

Delta compression will not be attempted for blobs for paths with theattribute delta set to false.

Viewing files in GUI tools

encoding

The value of this attribute specifies the character encoding that shouldbe used by GUI tools (e.g. gitk[1] and git-gui[1]) todisplay the contents of the relevant file. Note that due to performanceconsiderations gitk[1] does not use this attribute unless youmanually enable per-file encodings in its options.

If this attribute is not set or has an invalid value, the value of thegui.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 diffsproduced for, any binary file you track. You would need to specify e.g.

  1. *.jpg -text -diff

but that may become cumbersome, when you have many attributes. Usingmacro attributes, you can define an attribute that, when set, alsosets or unsets a number of other attributes at the same time. Thesystem knows a built-in macro attribute, binary:

  1. *.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 otherattributes or even returning other attributes to the "Unspecified"state.

DEFINING MACRO ATTRIBUTES

Custom macro attributes can be defined only in top-level gitattributesfiles ($GIT_DIR/info/attributes, the .gitattributes file at thetop level of the working tree, or the global or system-widegitattributes files), not in .gitattributes files in working treesubdirectories. The built-in macro attribute "binary" is equivalentto:

  1. [attr]binary -diff -merge -text

EXAMPLES

If you have these three gitattributes file:

  1. (in $GIT_DIR/info/attributes)
  2.  
  3. a* foo !bar -baz
  4.  
  5. (in .gitattributes)
  6. abc foo bar baz
  7.  
  8. (in t/.gitattributes)
  9. ab* merge=filfre
  10. abc -foo -bar
  11. *.c frotz

the attributes given to path t/abc are computed as follows:

  • By examining t/.gitattributes (which is in the samedirectory as the path in question), Git finds that the firstline matches. merge attribute is set. It also finds thatthe second line matches, and attributes foo and barare unset.

  • Then it examines .gitattributes (which is in the parentdirectory), and finds that the first line matches, butt/.gitattributes file already decided how merge, fooand bar attributes should be given to this path, so itleaves foo and bar unset. Attribute baz is set.

  • Finally it examines $GIT_DIR/info/attributes. This fileis used to override the in-tree settings. The first line isa match, and foo is set, bar is reverted to unspecifiedstate, and baz is unset.

As the result, the attributes assignment to t/abc becomes:

  1. foo set to true
  2. bar unspecified
  3. baz set to false
  4. merge set to string value "filfre"
  5. frotz unspecified

SEE ALSO

git-check-attr[1].

GIT

Part of the git[1] suite