Linux "gitattributes" Command Line Options and Examples
defining attributes per path

A gitattributes file is a simple text file that gives attributes to pathnames. Each line in gitattributes file is of form: pattern attr1 attr2 ..


Usage:

$GIT_DIR/info/attributes, .gitattributes






Command Line Options:

-crlf
crlf=input eol=lfEnd-of-line conversionWhile 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 canset the config variable "core.autocrlf" without using any attributes.[core]autocrlf = trueThis does not force normalization of text files, but does ensure that text files that you introduce to the repository have theirline 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, youcan set the text attribute to "auto" for all files.* text=autoThe 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 .jpgfiles from being normalized regardless of their content.* text=auto*.txt text*.vcproj text eol=crlf*.sh text eol=lf*.jpg -textNoteWhen text=auto conversion is enabled in a cross-platform project using push and pull to a central repository the text filescontaining 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 -textConversely, text files that Git does not detect can have normalization enabled manually.weirdchars.txt textIf core.safecrlf is set to "true" or "warn", Git verifies if the conversion is reversible for the current setting ofcore.autocrlf. For "true", Git rejects irreversible conversions; for "warn", Git only prints a warning but accepts anirreversible conversion. The safety triggers to prevent such a conversion done to the files in the work tree, but there are a fewexceptions. 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 andCRLF 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.identWhen the attribute ident is set for a path, Git replaces $Id$ in the blob object with $Id:, followed by the 40-characterhexadecimal 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.filterA 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, whenthe smudge command is specified, the command is fed the blob object from its standard input, and its standard output is used toupdate the worktree file. Similarly, the clean command is used to convert the contents of worktree file upon checkin. By defaultthese commands process only a single blob and terminate. If a long running process filter is used in place of clean and/or smudgefilters, then Git can process all blobs with a single filter command invocation for the entire life of a single Git command, forexample git add --all. If a long running process filter is configured then it always takes precedence over a configured singleblob 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, andthe user to use. For this mode of operation, the key phrase here is "more convenient" and not "turning something unusable intousable". In other words, the intent is that if someone unsets the filter driver definition, or does not have the appropriatefilter 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 thatrefers 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 moreconvenient shape. A missing filter driver definition in the config, or a filter driver that exits with a non-zero status, is notan 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 thefilter.<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=indentThen you would define a "filter.indent.clean" and "filter.indent.smudge" configuration in your .git/config to specify a pair ofcommands to modify the contents of C programs when the source files are checked in ("clean" is run) and checked out (no change ismade because the command is "cat").[filter "indent"]clean = indentsmudge = catFor 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 thesection 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 theconfiguration:[filter "crypt"]clean = openssl enc ...smudge = openssl enc -d ...requiredSequence "%f" on the filter command line is replaced with the name of the file the filter is working on. A filter might use thisin keyword substitution. For example:[filter "p4"]clean = git-p4-filter --clean %fsmudge = git-p4-filter --smudge %fNote that "%f" is the name of the path that is being worked on. Depending on the version that is being filtered, thecorresponding file on disk may not exist, or may have different contents. So, smudge and clean commands should not try to accessthe file on disk, but only act as filters on the content provided to them on standard input.Long Running Filter ProcessIf the filter command (a string value) is defined via filter.<driver>.process then Git can process all blobs with a single filterinvocation for the entire life of a single Git command. This is achieved by using the long-running process protocol (described intechnical/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 thehandshake, the welcome message sent by Git is "git-filter-client", only version 2 is suppported, and the supported capabilitiesare "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 filtercommand (based on the supported capabilities) and the pathname of the file to filter relative to the repository root. Right afterthe flush packet Git sends the content split in zero or more pkt-line packets and a flush packet to terminate content. Pleasenote, 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=smudgepacket: git> pathname=path/testfile.datpacket: git> 0000packet: git> CONTENTpacket: git> 0000The filter is expected to respond with a list of "key=value" pairs terminated with a flush packet. If the filter does notexperience problems then the list must contain a "success" status. Right after these packets the filter is expected to send thecontent in zero or more pkt-line packets and a flush packet at the end. Finally, a second list of "key=value" pairs terminatedwith 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=successpacket: git< 0000packet: git< SMUDGED_CONTENTpacket: git< 0000packet: 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 theempty content.packet: git< status=successpacket: git< 0000packet: 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=errorpacket: git< 0000If the filter experiences an error during processing, then it can send the status "error" after the content was (partially orcompletely) sent.packet: git< status=successpacket: git< 0000packet: git< HALF_WRITTEN_ERRONEOUS_CONTENTpacket: git< 0000packet: git< status=errorpacket: git< 0000In case the filter cannot or does not want to process the content as well as any future content for the lifetime of the Gitprocess, then it is expected to respond with an "abort" status at any point in the protocol.packet: git< status=abortpacket: git< 0000Git 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 the behavior of the filter.<driver>.clean / filter.<driver>.smudgemechanism.If the filter dies during the communication or does not adhere to the protocol then Git will stop the filter process and restartit with the next file that needs to be processed. Depending on the filter.<driver>.required flag Git will interpret that aserror.DelayIf the filter supports the "delay" capability, then Git can send the flag "can-delay" after the filter command and pathname. Thisflag denotes that the filter can delay filtering the current blob (e.g. to compensate network latencies) by responding with nocontent but with the status "delayed" and a flush packet.packet: git> command=smudgepacket: git> pathname=path/testfile.datpacket: git> can-delay=1packet: git> 0000packet: git> CONTENTpacket: git> 0000packet: git< status=delayedpacket: git< 0000If 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 nowavailable. The list must be terminated with a flush packet followed by a "success" status that is also terminated with a flushpacket. If no blobs for the delayed paths are available, yet, then the filter is expected to block the response until at leastone blob becomes available. The filter can tell Git that it has no more delayed blobs by sending an empty list. As soon as thefilter responds with an empty list, Git stops asking. All blobs that Git has not received at this point are considered missingand will result in an error.packet: git> command=list_available_blobspacket: git> 0000packet: git< pathname=path/testfile.datpacket: git< pathname=path/otherfile.datpacket: git< 0000packet: git< status=successpacket: git< 0000After Git received the pathnames, it will request the corresponding blobs again. These requests contain a pathname and an emptycontent section. The filter is expected to respond with the smudged content in the usual way as explained above.packet: git> command=smudgepacket: git> pathname=path/testfile.datpacket: git> 0000packet: git> 0000 # empty content!packet: git< status=successpacket: git< 0000packet: git< SMUDGED_CONTENTpacket: git< 0000packet: git< 0000 # empty list, keep "status=success" unchanged!ExampleA long running filter demo implementation can be found in contrib/long-running-filter/example.pl located in the Git corerepository. If you develop your own long running filter process then the GIT_TRACE_PACKET environment variables can be veryhelpful for debugging (see git(1)).Please note that you cannot use an existing filter.<driver>.clean or filter.<driver>.smudge command with filter.<driver>.processbecause the former two use a different inter process communication protocol than the latter one.Interaction between checkin/checkout attributesIn the check-in codepath, the worktree file is first converted with filter driver (if specified and corresponding driverdefined), then the result is processed with ident (if specified), and then finally with text (again, if specified andapplicable).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 attributesIf you have added attributes to a file that cause the canonical repository format for that file to change, such as adding aclean/smudge filter or text/eol/ident attributes, merging anything where the attribute is not in place would normally cause mergeconflicts.To prevent these unnecessary merge conflicts, Git can be told to run a virtual check-out and check-in of all three stages of afile when resolving a three-way merge by setting the merge.renormalize configuration variable. This prevents changes caused bycheck-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 willautomatically resolve all filter-related conflicts. Filters that do not act in this way may cause additional merge conflicts thatmust be resolved manually.Generating diff textdiffThe attribute diff affects how Git generates diffs for particular files. It can tell Git whether to generate a textual patch forthe 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 generatingthe diff.SetA path to which the diff attribute is set is treated as text, even when they contain byte values that normally never appearin text files, such as NUL.UnsetA path to which the diff attribute is unset will generate Binary files differ (or a binary patch, if binary patches areenabled).UnspecifiedA path to which the diff attribute is unspecified first gets its contents inspected, and if it looks like text and is smallerthan core.bigFileThreshold, it is treated as text. Otherwise it would generate Binary files differ.StringDiff is shown using the specified diff driver. Each driver may specify one or more options, as described in the followingsection. The options for the diff driver "foo" are defined by the configuration variables in the "diff.foo" section of theGit config file.Defining an external diff driverThe definition of a diff driver is done in gitconfig, not gitattributes file, so strictly speaking this manual page is a wrongplace 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-diffWhen Git needs to show you a diff for the path with diff attribute set to jcdiff, it calls the command you specified with theabove configuration, i.e. j-c-diff, with 7 parameters, just like GIT_EXTERNAL_DIFF program is called. See git(1) for details.Defining a custom hunk-headerEach group of changes (called a "hunk") in the textual diff output is prefixed with a line of the form:@@ -k,l +n,m @@ TEXTThis is called a hunk header. The "TEXT" portion is by default a line that begins with an alphabet, an underscore or a dollarsign; this matches what GNU diff -p output uses. This default selection however is not suited for some contents, and you can usea customized pattern to make a selection.First, in .gitattributes, you would assign the diff attribute for paths.*.tex diff=texThen, you would define a "diff.tex.xfuncname" configuration to specify 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:[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; thepattern above picks a line that begins with a backslash, and zero or more occurrences of sub followed by section followed by openbrace, 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 yourconfiguration file (you still need to enable this with the attribute 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 language.· 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.· tex suitable for source code for LaTeX documents.Customizing word diffYou can customize the rules that git diff --word-diff uses to split words in a line, by specifying an appropriate regularexpression in the "diff.*.wordRegex" configuration variable. For example, in TeX a backslash followed by a sequence of lettersforms a command, but several such commands can be run together without intervening whitespace. To separate them, use a regularexpression 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 filesSometimes it is desirable to see the diff of a text-converted version of some binary files. For example, a word processordocument can be converted to an ASCII text representation, and the diff of the text shown. Even though this conversion loses someinformation, 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 singleargument, 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 exiftool installed), add the following section to your $GIT_DIR/config file (or $HOME/.gitconfig file):[diff "jpg"]textconv = exifNoteThe text conversion is generally a one-way conversion; in this example, we lose the actual image contents and focus just onthe text data. This means that diffs generated by textconv are not suitable for applying. For this reason, only git diff andthe git log family of commands (i.e., log, whatchanged, show) will perform text conversion. git format-patch will nevergenerate this output. If you want to send somebody a text-converted diff of a binary file (e.g., because it quickly conveysthe changes you have made), you should generate it separately and send it as a comment in addition to the usual binary diffthat 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 tocache 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 = exifcachetextconv = trueThis will cache the result of running "exif" on each blob indefinitely. If you change the textconv config variable for a diffdriver, Git will automatically invalidate the cache entries and re-run the textconv filter. If you want to invalidate the cachemanually (e.g., because your version of "exif" was updated and now produces better output), you can remove the cache manuallywith 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 diffIf you want to show differences between binary or specially-formatted blobs in your repository, you can choose to use either anexternal diff command, or to use textconv to convert them to a diff-able text format. Which method you choose depends on yourexact situation.The advantage of using an external diff command is flexibility. You are not bound to find line-oriented changes, nor is itnecessary for the output to resemble unified diff. You are free to locate and report changes in the most appropriate way for yourdata format.A textconv, by comparison, is much more limiting. You provide a transformation of the data into a line-oriented text format, andGit 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 manycases, 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 binaryGit 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 thecontent, while technically composed of text characters, is opaque to a human reader. For example, many postscript files containonly 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 -diffThis 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 convertpostscript files to an ASCII representation for human viewing, but otherwise treat them as binary files. You cannot specify both
gitattributes -crlf ...
-diff
[diff "ps"]textconv = ps2asciibinary = truePerforming a three-way mergemergeThe attribute merge affects how three versions of a file are merged when a file-level merge is necessary during git merge, andother commands such as git revert and git cherry-pick.SetBuilt-in 3-way merge driver is used to merge the contents in a way similar to merge command of RCS suite. This is suitablefor ordinary text files.UnsetTake the version from the current branch as the tentative merge result, and declare that the merge has conflicts. This issuitable for binary files that do not have a well-defined merge semantics.UnspecifiedBy default, this uses the same built-in 3-way merge driver as is the case when the merge attribute is set. However, themerge.default configuration variable can name different merge driver to be used with paths for which the merge attribute isunspecified.String
gitattributes -diff ...