что делает команда git show
Всем привет. Мы продолжаем изучать гит. И давайте напишем какую-то полезную функцию в наш файл 1.js, который мы создали на прошлом уроке.
Если мы напишем git status, то увидим, что у нас есть модифицированные файлы и гит видит, что мы что-то изменили. Давайте посмотрим как гит видит наши изменения. Для этого воспользуемся командой
Нам в консоль вывелся только 1 файл, который был изменен. Зеленым показаны строчки, которые были добавлены, а красным которые удалены. Сейчас мы видим только зеленые строчки.
Давайте закоммитим наши изменения как в прошлом уроке. Для этого напишем
чтобы зафиксировать наши изменения.
Чтобы создать коммит.
Если мы напишем git log, то увидим, что у нас сейчас уже 2 коммита. Первый коммит с прошлого урока и коммит, который мы добавили только что.
Если вдруг коммитов у нас много и мы хотим посмотреть изменения определенного коммита, то мы можем написать команду git show и указать id коммита.
И на экране мы видим то же самое, что мы видели, когда смотрели дифф незакоммиченых файлов.
Давайте изменим функцию в файле на функцию отнимания
Если мы теперь напишем git diff, то нам выведемтся в консоль красным что мы удалили, а зеленым что добавили. Мы удалили слово add и добавили deduct, так же мы поменяли плюс на минус. И гит все эти изменения трекает. Давайте закоммитим это изменения тоже.
Как мы видим, гит позволяет сохранять абсолютно все изменения файлов вплоть до последней буквы, что помогает хранить историю любов давности и легко понимать кто и когда и какие изменения сделал.
Что делает команда git show
Check your version of git by running
SYNOPSIS
DESCRIPTION
Shows one or more objects (blobs, trees, tags and commits).
For tags, it shows the tag message and the referenced objects.
For plain blobs, it shows the plain contents.
The command takes options applicable to the git diff-tree command to control how the changes the commit introduces are shown.
This manual page describes only the most frequently used options.
OPTIONS
The names of objects to show (defaults to HEAD). For a more complete list of ways to spell object names, see «SPECIFYING REVISIONS» section in gitrevisions[7].
See the «PRETTY FORMATS» section for some additional details for each format. When = part is omitted, it defaults to medium.
Note: you can specify the default pretty format in the repository configuration (see git-config[1]).
Instead of showing the full 40-byte hexadecimal commit object name, show a prefix that names the object uniquely. «—abbrev= » (which also modifies diff output, if it is displayed) option can be used to specify the minimum length of the prefix.
This should make «—pretty=oneline» a whole lot more readable for people using 80-column terminals.
By default, tabs are expanded in pretty formats that indent the log message by 4 spaces (i.e. medium, which is the default, full, and fuller).
By default, the notes shown are from the notes refs listed in the core.notesRef and notes.displayRef variables (or corresponding environment overrides). See git-config[1] for more details.
PRETTY FORMATS
If the commit is a merge, and if the pretty-format is not oneline, email or raw, an additional line is inserted before the Author: line. This line begins with «Merge: » and the hashes of ancestral commits are printed, separated by spaces. Note that the listed commits may not necessarily be the list of the direct parent commits if you have limited your view of history: for example, if you are only interested in changes related to a certain directory or file.
There are several built-in formats, and you can define additional formats by setting a pretty. config option to either another format name, or a format: string, as described below (see git-config[1]). Here are the details of the built-in formats:
This is designed to be as compact as possible.
Like email, but lines in the commit message starting with «From » (preceded by zero or more «>») are quoted with «>» so they aren’t confused as starting a new commit.
The format: format allows you to specify which information you want to show. It works a little bit like printf format, with the notable exception that you get a newline with %n instead of \n.
E.g, format:»The author of %h was %an, %ar%nThe title was >>%s %n
print a byte from a hex code
Placeholders that affect formatting of later placeholders:
switch color to red
switch color to green
switch color to blue
make the next placeholder take at least N columns, padding spaces on the right if necessary. Optionally truncate at the beginning (ltrunc), the middle (mtrunc) or the end (trunc) if the output is longer than N columns. Note that truncating only works correctly with N >= 2.
make the next placeholder take at least until Nth columns, padding spaces on the right if necessary
similar to % ), % ) respectively, but padding spaces on the left
similar to %>( ), %>|( ) respectively, except that if the next placeholder takes more spaces than given and there are spaces on its left, use those spaces
similar to % ), % ) respectively, but padding both sides (i.e. the text is centered)
Placeholders that expand to information extracted from the commit:
abbreviated commit hash
abbreviated tree hash
abbreviated parent hashes
author email local-part (the part before the @ sign)
author date, RFC2822 style
author date, relative
author date, UNIX timestamp
author date, ISO 8601-like format
author date, strict ISO 8601 format
author date, short format ( YYYY-MM-DD )
committer email local-part (the part before the @ sign)
committer date, RFC2822 style
committer date, relative
committer date, UNIX timestamp
committer date, ISO 8601-like format
committer date, strict ISO 8601 format
committer date, short format ( YYYY-MM-DD )
ref names without the » («, «)» wrapping.
human-readable name, like git-describe[1]; empty string for undescribable commits. The describe string may be followed by a colon and zero or more comma-separated options. Descriptions can be inconsistent when tags are added or removed at the same time.
: Only consider tags matching the given glob(7) pattern, excluding the «refs/tags/» prefix.
: Do not consider tags matching the given glob(7) pattern, excluding the «refs/tags/» prefix.
sanitized subject line, suitable for a filename
raw body (unwrapped subject and body)
raw verification message from GPG for a signed commit
show «G» for a good (valid) signature, «B» for a bad signature, «U» for a good signature with unknown validity, «X» for a good signature that has expired, «Y» for a good signature made by an expired key, «R» for a good signature made by a revoked key, «E» if the signature cannot be checked (e.g. missing key) and «N» for no signature
show the name of the signer for a signed commit
show the key used to sign a signed commit
show the fingerprint of the key used to sign a signed commit
show the fingerprint of the primary key whose subkey was used to sign a signed commit
show the trust level for the key used to sign a signed commit
reflog identity name
reflog identity email
display the trailers of the body as interpreted by git-interpret-trailers[1]. The trailers string may be followed by a colon and zero or more comma-separated options. If any option is provided multiple times the last occurrence wins.
only[= ]: select whether non-trailer lines from the trailer block should be included.
separator= : specify a separator inserted between trailer lines. When this option is not given each trailer line is terminated with a line feed character. The string SEP may contain the literal formatting codes described above. To use comma as separator one must use %x2C as it would otherwise be parsed as next option. E.g., %(trailers:key=Ticket,separator=%x2C ) shows all trailer lines whose key is «Ticket» separated by a comma and a space.
keyonly[= ]: only show the key part of the trailer.
valueonly[= ]: only show the value part of the trailer.
key_value_separator= : specify a separator inserted between trailer lines. When this option is not given each trailer key-value pair is separated by «: «. Otherwise it shares the same semantics as separator= above.
If you add a + (plus sign) after % of a placeholder, a line-feed is inserted immediately before the expansion if and only if the placeholder expands to a non-empty string.
If you add a ` ` (space) after % of a placeholder, a space is inserted immediately before the expansion if and only if the placeholder expands to a non-empty string.
The tformat: format works exactly like format:, except that it provides «terminator» semantics instead of «separator» semantics. In other words, each commit has the message terminator character (usually a newline) appended, rather than a separator placed between entries. This means that the final entry of a single-line format will be properly terminated with a new line, just as the «oneline» format does. For example:
In addition, any unrecognized string that has a % in it is interpreted as if it has tformat: in front of it. For example, these two are equivalent:
DIFF FORMATTING
The options below can be used to change the way git show generates diff output.
Generate patch (see section on generating patches).
Disable output of diffs for merge commits. Useful to override implied value.
This option makes merge commits show the full diff with respect to the first parent only.
This makes merge commits show the full diff with respect to each of the parents. Separate log entry and diff is generated for each parent.
Output to a specific file instead of stdout.
Specify the character used to indicate new, old or context lines in the generated patch. Normally they are +, — and ‘ ‘ respectively.
Show the tree objects in the diff output.
Enable the heuristic that shifts diff hunk boundaries to make patches easier to read. This is the default.
Disable the indent heuristic.
Spend extra time to make sure the smallest possible diff is produced.
Generate a diff using the «patience diff» algorithm.
Generate a diff using the «histogram diff» algorithm.
Generate a diff using the «anchored diff» algorithm.
This option may be specified more than once.
If a line exists in both the source and destination, exists only once, and starts with this text, this algorithm attempts to prevent it from appearing as a deletion or addition in the output. It uses the «patience diff» algorithm internally.
Choose a diff algorithm. The variants are as follows:
The basic greedy diff algorithm. Currently, this is the default.
Spend extra time to make sure the smallest possible diff is produced.
Use «patience diff» algorithm when generating patches.
This algorithm extends the patience algorithm to «support low-occurrence common elements».
Compute the dirstat numbers by counting the lines that have been removed from the source, or added to the destination. This ignores the amount of pure code movements within a file. In other words, rearranging lines in a file is not counted as much as other changes. This is the default behavior when no parameter is given.
An integer parameter specifies a cut-off percent (3% by default). Directories contributing less than this percentage of the changes are not shown in the output.
Output a condensed summary of extended header information such as creations, renames and mode changes.
Separate the commits with NULs instead of with new newlines.
Without this option, pathnames with «unusual» characters are quoted as explained for the configuration variable core.quotePath (see git-config[1]).
Show only names of changed files. The file names are often encoded in UTF-8. For more information see the discussion about encoding in the git-log[1] manual page.
Moved lines of code are colored differently. The defaults to no if the option is not given and to zebra if the option with no mode is given. The mode must be one of:
Moved lines are not highlighted.
Any line that is added in one location and was removed in another location will be colored with color.diff.newMoved. Similarly color.diff.oldMoved will be used for removed lines that are added somewhere else in the diff. This mode picks up any moved line, but it is not very useful in a review to determine if a block of code was moved without permutation.
Blocks of moved text of at least 20 alphanumeric characters are detected greedily. The detected blocks are painted using either the color.diff.
Blocks of moved text are detected as in blocks mode. The blocks are painted using either the color.diff.
Similar to zebra, but additional dimming of uninteresting parts of moved code is performed. The bordering lines of two adjacent blocks are considered interesting, the rest is uninteresting. dimmed_zebra is a deprecated synonym.
Do not ignore whitespace when performing move detection.
Ignore changes in whitespace at EOL.
Ignore changes in amount of whitespace. This ignores whitespace at line end, and considers all other sequences of one or more whitespace characters to be equivalent.
Ignore whitespace when comparing lines. This ignores differences even if one line has whitespace where the other line has none.
Initially ignore any whitespace in the move detection, then group the moved code blocks only into a block if the change in whitespace is the same per line. This is incompatible with the other modes.
Show words as [-removed-] and <+added+>. Makes no attempts to escape the delimiters if they appear in the input, so the output may be ambiguous.
on a line of its own.
Disable word diff again.
Note that despite the name of the first mode, color is used to highlight the changed parts in all modes if enabled.
Every non-overlapping match of the is considered a word. Anything between these matches is considered whitespace and ignored(!) for the purposes of finding differences. You may want to append |[^[:space:]] to your regular expression to make sure that it matches all non-whitespace characters. A match that contains a newline is silently truncated(!) at the newline.
The regex can also be set via a diff driver or configuration option, see gitattributes[5] or git-config[1]. Giving it explicitly overrides any diff driver or configuration setting. Diff drivers override configuration settings.
Turn off rename detection, even when the configuration file gives the default to do so.
Whether to use empty blobs as rename source.
Instead of the first handful of characters, show the full pre- and post-image blob object names on the «index» line when generating patch format output.
Break complete rewrite changes into pairs of delete and create. This serves two purposes:
Select only files that are Added ( A ), Copied ( C ), Deleted ( D ), Modified ( M ), Renamed ( R ), have their type (i.e. regular file, symlink, submodule, …) changed ( T ), are Unmerged ( U ), are Unknown ( X ), or have had their pairing Broken ( B ). Any combination of the filter characters (including none) can be used. When * (All-or-none) is added to the combination, all paths are selected if there is any file that matches other criteria in the comparison; if there is no file that matches other criteria, nothing is selected.
Note that not all diffs can feature all types. For instance, diffs from the index to the working tree can never have Added entries (because the set of paths included in the diff is limited by what is in the index). Similarly, copied and renamed entries cannot appear if detection for those types is disabled.
Look for differences that change the number of occurrences of the specified string (i.e. addition/deletion) in a file. Intended for the scripter’s use.
Binary files are searched as well.
See the pickaxe entry in gitdiffcore[7] for more information.
is parsed as follows:
Blank lines are ignored, so they can be used as separators for readability.
Lines starting with a hash (» # «) are ignored, so they can be used for comments. Add a backslash (» \ «) to the beginning of the pattern if it starts with a hash.
Each other line contains a single pattern.
Patterns have the same syntax and semantics as patterns used for fnmatch(3) without the FNM_PATHNAME flag, except a pathname also matches a pattern if removing any number of the final pathname components matches the pattern. For example, the pattern » foo*bar » matches » fooasdfbar » and » foo/bar/baz/asdf » but not » foobarx «.
Discard the files before the named from the output (i.e. skip to), or move them to the end of the output (i.e. rotate to). These were invented primarily for use of the git difftool command, and may not be very useful otherwise.
Swap two inputs; that is, show differences from index or on-disk file to tree contents.
When run from a subdirectory of the project, it can be told to exclude changes outside the directory and show pathnames relative to it with this option. When you are not in a subdirectory (e.g. in a bare repository), you can name which subdirectory to make the output relative to by giving a
Treat all files as text.
Ignore carriage-return at the end of line when doing a comparison.
Ignore changes in whitespace at EOL.
Ignore changes in amount of whitespace. This ignores whitespace at line end, and considers all other sequences of one or more whitespace characters to be equivalent.
Ignore whitespace when comparing lines. This ignores differences even if one line has whitespace where the other line has none.
Ignore changes whose lines are all blank.
Show the context between diff hunks, up to the specified number of lines, thereby fusing hunks that are close to each other. Defaults to diff.interHunkContext or 0 if the config option is unset.
Show whole function as context lines for each change. The function names are determined in the same way as git diff works out patch hunk headers (see Defining a custom hunk-header in gitattributes[5]).
Allow an external diff helper to be executed. If you set an external diff driver with gitattributes[5], you need to use this option with git-log[1] and friends.
Disallow external diff drivers.
Allow (or disallow) external text conversion filters to be run when comparing binary files. See gitattributes[5] for details. Because textconv filters are typically a one-way conversion, the resulting diff is suitable for human consumption, but cannot be applied. For this reason, textconv filters are enabled by default only for git-diff[1] and git-log[1], but not for git-format-patch[1] or diff plumbing commands.
Ignore changes to submodules in the diff generation. can be either «none», «untracked», «dirty» or «all», which is the default. Using «none» will consider the submodule modified when it either contains untracked or modified files or its HEAD differs from the commit recorded in the superproject and can be used to override any settings of the ignore option in git-config[1] or gitmodules[5]. When «untracked» is used submodules are not considered dirty when they only contain untracked content (but they are still scanned for modified content). Using «dirty» ignores all changes to the work tree of submodules, only changes to the commits stored in the superproject are shown (this was the behavior until 1.7.0). Using «all» hides all changes to submodules.
The a/ and b/ filenames are the same unless rename/copy is involved. Especially, even for a creation or a deletion, /dev/null is not used in place of the a/ or b/ filenames.
When rename/copy is involved, file1 and file2 show the name of the source file of the rename/copy and the name of the file that rename/copy produces, respectively.
It is followed by one or more extended header lines:
File modes are printed as 6-digit octal numbers including the file type and file permission bits.
Path names in extended headers do not include the a/ and b/ prefixes.
The similarity index is the percentage of unchanged lines, and the dissimilarity index is the percentage of changed lines. It is a rounded down integer, followed by a percent sign. The similarity index value of 100% is thus reserved for two equal files, while 100% dissimilarity means that no line from the old file made it into the new one.
The index line includes the blob object names before and after the change. The is included if the file mode does not change; otherwise, separate lines indicate the old and the new mode.
Pathnames with «unusual» characters are quoted as explained for the configuration variable core.quotePath (see git-config[1]).
All the file1 files in the output refer to files before the commit, and all the file2 files refer to files after the commit. It is incorrect to apply each change to each file sequentially. For example, this patch will swap a and b:
Hunk headers mention the name of the function to which the hunk applies. See «Defining a custom hunk-header» in gitattributes[5] for details of how to tailor to this to specific languages.
Combined diff format
A «combined diff» format looks like this:
It is followed by one or more extended header lines (this example shows a merge with two parents):
It is followed by two-line from-file/to-file header
Similar to two-line header for traditional unified diff format, /dev/null is used to signal created or deleted files.
This extended format can be useful if rename or copy detection is active, to allow you to see the original name of the file in different parents.
There are (number of parents + 1) @ characters in the chunk header for combined diff format.
EXAMPLES
git show master:Makefile master:t/Makefile
DISCUSSION
Git is to some extent character encoding agnostic.
The contents of the blob objects are uninterpreted sequences of bytes. There is no encoding translation at the core level.
Note that Git at the core level treats path names simply as sequences of non-NUL bytes, there are no path name encoding conversions (except on Mac and Windows). Therefore, using non-ASCII path names will mostly work even on platforms and file systems that use legacy extended ASCII encodings. However, repositories created on such systems will not work properly on UTF-8-based systems (e.g. Linux, Mac, Windows) and vice versa. Additionally, many Git-based tools simply assume path names to be UTF-8 and will fail to display other encodings correctly.
Commit log messages are typically encoded in UTF-8, but other extended ASCII encodings are also supported. This includes ISO-8859-x, CP125x and many others, but not UTF-16/32, EBCDIC and CJK multi-byte encodings (GBK, Shift-JIS, Big5, EUC-x, CP9xx etc.).
Although we encourage that the commit log messages are encoded in UTF-8, both the core and Git Porcelain are designed not to force UTF-8 on projects. If all participants of a particular project find it more convenient to use legacy encodings, Git does not forbid it. However, there are a few things to keep in mind.
Commit objects created with the above setting record the value of i18n.commitEncoding in its encoding header. This is to help other people who look at them later. Lack of this header implies that the commit log message is encoded in UTF-8.
If you do not have this configuration variable, the value of i18n.commitEncoding is used instead.
Note that we deliberately chose not to re-code the commit log message when a commit is made to force UTF-8 at the commit object level, because re-coding to UTF-8 is not necessarily a reversible operation.