How can I generate a git diff of what's change

2019-01-16 01:54发布

问题:

I'd like to script, preferably in rake, the following actions into a single command:

  1. Get the version of my local git repository.
  2. Git pull the latest code.
  3. Git diff from the version I extracted in step #1 to what is now in my local repository.

In other words, I want to get the latest code form the central repository and immediately generate a diff of what's changed since the last time I pulled.

回答1:

You could do this fairly simply with refspecs.

git pull origin
git diff @{1}..

That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version:

current=`git rev-parse HEAD`
git pull origin
git diff $current..

I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch:

git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..


回答2:

Greg's way should work (not me, other Greg :P). Regarding your comment, origin is a configuration variable that is set by Git when you clone the central repository to your local machine. Essentially, a Git repository remembers where it came from. You can, however, set these variables manually if you need to using git-config.

git config remote.origin.url <url>

where url is the remote path to your central repository.

Here is an example batch file that should work (I haven't tested it).

@ECHO off

:: Retrieve the changes, but don't merge them.
git fetch

:: Look at the new changes
git diff ...origin

:: Ask if you want to merge the new changes into HEAD
set /p PULL=Do you wish to pull the changes? (Y/N)
IF /I %PULL%==Y git pull


回答3:

This is very similar to a question I asked about how to get changes on a branch in git. Note that the behaviour of git diff vs. git log is inconsistently different when using two dots vs. three dots. But, for your application you can use:

git fetch
git diff ...origin

After that, a git pull will merge the changes into your HEAD.



回答4:

If you drop this into your bash profile you'll be able to run grin (git remote incoming) and grout (git remote outgoing) to see diffs of commits that are incoming and outgoing for origin master.

function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
}
function gd2 { 
 echo branch \($1\) has these commits and \($2\) does not 
 git log $2..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}
function grin {
 git fetch origin master
 gd2 FETCH_HEAD $(parse_git_branch)
}
function grout {
 git fetch origin master
 gd2 $(parse_git_branch) FETCH_HEAD
}


标签: git diff rake pull