Is there a command in Git to see (either dumped to stdout, or in $PAGER or $EDITOR) a particular version of a particular file?
Is there a command in Git to see (either dumped to stdout, or in $PAGER or $EDITOR) a particular version of a particular file?
You can use git show with a path from the root of the repository (./ or ../ for relative pathing):
$ git show REVISION:path/to/file
Replace REVISION with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)
For example, to view the version of file <repository-root>/src/main.c from 4 commits ago, use:
$ git show HEAD~4:src/main.c
Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show.
To quickly see the differences with older revisions of a file:
git show -1 filename.txt> to compare against the last revision of file
git show -2 filename.txt> to compare against the 2nd last revision
git show -3 fielname.txt> to compare against the last 3rd last revision
WAY 1: (I prefer this way, no ability to lose uncommitted data)
Find commit id with: git reflog
List files from commit git diff-tree --no-commit-id --name-only -r <commitHash>
Example:
git diff-tree --no-commit-id --name-only -r d2f9ba4
d2f9ba4is commit id from step 1.
Open required file with following command:
git show <commitHash>:/path/to/file
Example:
git show d2f9ba4:Src/Ext/MoreSwiftUI/ListCustom.swift
Src/...is file path from step 2.
WAY 2: (Ability to lose uncommitted data)
Find commit id with: git reflog
Make hard reset to this commit: git reset --hard %commit ID%
Example:
git reset --hard c14809fa
Make necessary changes and do a new commit into required branch
You can use a script like this to dump all the versions of a file to separate files:
e.g.
git_dump_all_versions_of_a_file.sh path/to/somefile.txt
Get the script here as an answer to another similar question
Helper to fetch multiple files from a given revision
When trying to resolve merge conflicts, this helper is very useful:
#!/usr/bin/env python3
import argparse
import os
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('revision')
parser.add_argument('files', nargs='+')
args = parser.parse_args()
toplevel = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip().decode()
for path in args.files:
file_relative = os.path.relpath(os.path.abspath(path), toplevel)
base, ext = os.path.splitext(path)
new_path = base + '.old' + ext
with open(new_path, 'w') as f:
subprocess.call(['git', 'show', '{}:./{}'.format(args.revision, path)], stdout=f)
Usage:
git-show-save other-branch file1.c path/to/file2.cpp
Outcome: the following contain the alternate versions of the files:
file1.old.c
path/to/file2.old.cpp
This way, you keep the file extension so your editor won't complain, and can easily find the old file just next to the newer one.