Git 中是否有“ Git pull —— dry-run”选项?

有没有像 git pull --dry-run这样的东西,在它弄乱我的工作树之前,看看东西是如何被合并的?

现在我正在做:

git fetch origin && git merge --no-commit --no-ff

我在手册页中没有看到任何关于“ git-pull”的内容。

澄清一下,我只需要在 Ant 脚本中使用它来进行部署,以查看在执行 git pull时是否存在冲突,然后退出构建,失败部署,并保持目录树与 git pull之前相同。

64805 次浏览

You can get the effect you want by creating a new throw-away branch from your current one and doing the git pull there. If you're unhappy with the results, the original branch is intact.

I have always relied on the inherent abilities of Git to get me back if a merge fails.

To estimate how the merge might occur, you can start like you did with:

$ git fetch origin branch  # Fetch changes, but don't merge
$ git diff HEAD..origin/branch # Diff your current head to the fetched commit


... personal judgement of potential merge conflicts ...


$ git merge origin/branch # merge with the fetched commit

If things did not go as planned, look at your reflog and reset back to your desired state:

$ git reflog
...
abc987  HEAD@{0}: merge activity
b58aae8 HEAD@{1}: fetch origin/branch
8f3a362 HEAD@{2}: activity before the fetch
...
$ git reset --hard HEAD{2}

You will need to fetch first to update your local origin/master

git fetch origin

Then you can do:

git diff --name-only origin/master

Will list the files that have changed.

git diff origin/master directory_foo/file_bar.m

Will list the line by line diff of file directory_foo/file_bar.m.

Since pulling implies merging, I'd go with running git merge --abort if your script detects there were any conflicts and merging failed.

# fetch new commits from origin
$ git fetch


# check what are the differences and judge if safe to apply
$ git diff origin/master


# actually merge the fetched commits
$ git pull

See my answer in this similar question:

How to preview git-pull without doing fetch?

this goes to the ~/.gitconfig file:

[alias]
diffpull=!git fetch && git diff HEAD..@{u}

Since v2.27.0 there is a dry-run flag

Without pulling:

[ "$(git fetch;git diff | wc -l)" != "0" ] && (
echo there are updates
echo do your stuff here
)

or without touching anything:

[ "$(git pull --dry-run | wc -l)" != "0" ] && (
echo there are updates
echo do your stuff here
)

OliverE is spot-on: git pull has a dry-run option, so I recommend git pull --dry-run -v to achieve the OP's purpose -- simple and direct. pull did not always have a dry-run option but in previous (and current) versions of git, fetch did (and does) have a dry-run option. Thus, an alternative approach is to do a git fetch --dry-run -v before you do your pull. Always better to check on an action before executing it, than having to spend time reverting.