Git diff is a powerful command which allows you to see you recently made changes whether they are staged or not. There are however circumstances when you want to stash your diff on one branch and apply on other. We may also have to stash local changes in case we are going to fetch from remote and merge or rebase with destination branch.
Stashing and applying diff on the same machine is as easy as applying following commands,
git stash
// Do git pull/merge/rebase with destination branch
git stash pop // We can also do git stash apply stash@{0}
However, what if you made changes and want to apply that diff
on someone else’s workstation? We can follow the workflow below to apply it on the other machine.
Suppose I have following tracking protocol which houses a protocol method to track the tap,
protocol TrackingProtocol {
func trackTap(event: String)
}
However, I want to add one more method to track click to with click locations. Namely, xLocation
and yLocation
. So I make those changes and run git diff
to verify if they’re correct,
These changes are local to my machine. If I want to port them to someone else’s workstation, I will need to save them in the diff
file. I chose to save these diffs in file named track-click-location-additions.diff
git diff > ~/Desktop/track-click-location-additions.diff
Once we send this file over to someone else, they can store it on their machine and run git apply
to apply these changes
git apply ~/Desktop/track-click-location-additions.diff
This should be all and if you verify this diff now with git diff
command, you will see that all the changes have been correctly applied on your branch. And that’s the end of the happy path story.
What if I run into error: patch failed - patch does not apply
error message while applying patch?
There could be situations where you might run into error saying git failed to apply patch and concerned diff can no longer be applied
<diff file full path>: trailing whitespace.
error: patch failed: <full file path>
error: <full file path>: patch does not apply
According to one of the StackOverflow answers this happens because,
By default, git will warn about whitespace errors, but will still accept them. If they are hard errors then you must have changed some settings
But this is strange. I never changed any settings since last time I diff
‘ed and stored it in the local file. However, we can easily overcome this error by adding an extra argument namely --whitespace=warn
git apply --whitespace=warn ~/Desktop/track-click-location-additions.diff
In my case in other example, it warned me because my changes had trailing whitespaces,
But if I go back and explicitly remove these trailing spaces from original changes, it will stop complaining and outright apply that diff without any warning or complaint,
So that should be all for today’s post. To summarize, today we saw
- How to apply
diff
patch using Git command - How to overcome
error: patch failed
after applying thediff
- How to deal with trailing whitespace warning message after applying the
diff
References:
StackOverflow — My diff contains trailing whitespace — how to get rid of it?
I’m stuck right now. Patching was working previously, and I feel like I didn’t change anything… though I could be wrong….
I’m getting this error when I run composer update…:
Extracting archive — Applying patches for wpackagist-plugin/postcode-shipping
patches/post_codeShipping.patch (Add default param to method call)
cd ‘public/plugins/postcode-shipping’ && git —git-dir=. apply —check ‘-p1’ ‘/home/james/code/wordplate/app/patches/post_codeShipping.patch’
error: patch failed: postcode_shipping.php:561error: postcode_shipping.php: patch does not apply
cd ‘public/plugins/postcode-shipping’ && git —git-dir=. apply —check ‘-p0’ ‘/home/james/code/wordplate/app/patches/post_codeShipping.patch’
error: b/postcode_shipping.php: No such file or directorycd ‘public/plugins/postcode-shipping’ && git —git-dir=. apply —check ‘-p2’ ‘/home/james/code/wordplate/app/patches/post_codeShipping.patch’
fatal: unable to find filename in patch at line 1cd ‘public/plugins/postcode-shipping’ && git —git-dir=. apply —check ‘-p4’ ‘/home/james/code/wordplate/app/patches/post_codeShipping.patch’
fatal: unable to find filename in patch at line 1patch ‘-p1’ —no-backup-if-mismatch -d ‘public/plugins/postcode-shipping’ < ‘/home/james/code/wordplate/app/patches/post_codeShipping.patch’
(Stripping trailing CRs from patch; use —binary to disable.)patching file postcode_shipping.php
Hunk #1 FAILED at 346 (different line endings).
Hunk #2 FAILED at 561 (different line endings).
2 out of 2 hunks FAILED
— saving rejects to file postcode_shipping.php.rej
I’m guessing I can ignore error: patch failed:
errors, as it’s just looking in directories…?
I’m thinking that the actual problem is:
Hunk #1 FAILED at 346 (different line endings).
If so, how to I get around this?
I see:
(Stripping trailing CRs from patch; use —binary to disable.)
I see plenty of advice around the internets to run git apply with this:
-l or —ignore-white-space option
but not sure how to do this, with composer-patches, since this command is inside composer-patches core….
Any help gratefully appreciated
У меня есть определенный патч под названием my_pcc_branch.заплатка.
когда я пытаюсь применить его, я получаю следующее сообщение:
$ git apply --check my_pcc_branch.patch
warning: src/main/java/.../AbstractedPanel.java has type 100644, expected 100755
error: patch failed: src/main/java/.../AbstractedPanel.java:13
error: src/main/java/.../AbstractedPanel.java: patch does not apply
что это значит?
Как я могу решить эту проблему?
8 ответов
Йоханнес Сикст из msysgit@googlegroups.com список рассылки предлагается использовать следующие аргументы командной строки:
git apply --ignore-space-change --ignore-whitespace mychanges.patch
это решило мою проблему.
git apply --reject --whitespace=fix mychanges.patch
работал для меня.
эта команда применит патч, не разрешая его, оставляя плохие файлы как *.rej
:
git apply --reject --whitespace=fix mypath.patch
вы просто должны решить их. После разрешения выполнить:
git -am resolved
40
автор: Ivan Voroshilin
когда все остальное не удается, попробуйте git apply
‘ s --3way
опции.
git apply --3way patchFile.patch
—3 исхода
Когда патч не применяется чисто, отступите на 3-way merge, если
патч записывает идентификатор blobs, к которому он должен применяться, и мы
есть ли эти blobs доступны локально, возможно, оставляя конфликт
маркеры в файлах в рабочем дереве для разрешения пользователем. Этот
опция подразумевает опцию —index и несовместима с этот
—отклонить и кэшированные варианты.
типичный случай сбоя применяет столько патча, сколько может, и оставляет вас с конфликтами, чтобы работать в git, однако вы обычно это делаете. Вероятно, на один шаг легче, чем reject
альтернативы.
это происходит, когда вы смешиваете клиенты UNIX и Windows git, потому что Windows на самом деле не имеет понятия «x» бит, поэтому ваша проверка rw-r--r--
(0644) файл под Windows «продвигается» слоем MSYS POSIX, чтобы быть rwx-r-xr-x
(0755). git считает, что разница в режиме в основном такая же, как текстовая разница в файле, поэтому ваш патч не применяется напрямую. Я думаю, что ваш единственный хороший вариант здесь-установить core.filemode
to false
(через git-config
).
здесь проблема msysgit с некоторой связанной информацией:http://code.google.com/p/msysgit/issues/detail?id=164 (перенаправлено на archive.org ‘ S 3 Dec 2013 copy)
в моем случае я был достаточно глуп, чтобы создать файл патча неправильно в первую очередь, на самом деле diff-ing неправильный путь. Я закончил с теми же сообщениями об ошибках.
Если вы на master и do git diff branch-name > branch-name.patch
, Это пытается удалить все дополнения, которые вы хотите сделать, и наоборот (что было невозможно для git, поскольку, очевидно, никогда не выполненные дополнения не могут быть удалены).
поэтому убедитесь, что вы проверяете свою ветку и выполняете git diff master > branch-name.patch
Я нашел этой ссылке
Я понятия не имею, почему это работает, но я пробовал много обходных путей, и это единственный, который работал для меня. Короче говоря, выполните три команды ниже:
git fsck --full
git reflog expire --expire=now --all
git gc --prune=now
Ошибки и решения
Список ошибок и решений.
Настройки ~/.gitconfig
Чтобы не получать следующее предупреждение:
fatal: The current branch PROMO-43 has no upstream branch.
To push the current branch and set the remote as upstream, use
git push —set-upstream origin YOUR_BRANCH_NAME
можно пушить текущую ветку в одноименнюу удаленную ветку, поэтому я применяю такую настройку:
[push]
default = current
напомню, что значение этой настройки может быть одним из следующих:
- nothing: do not push anything
- matching: push all matching branches
All branches having the same name in both ends are considered to be matching.
This is the default in Git 1.x. - upstream: push the current branch to its upstream branch (tracking is a deprecated synonym for upstream)
- current: push the current branch to a branch of the same name
- simple: (new in Git 1.7.11) like upstream, but refuses to push if the upstream branch’s name is different from the local one
git apply trailing whitespace
Попробовал накатить патч и получил ошибки вида trailing whitespace после чего фигурировали error: patch failed
Попробовал разобраться сначала с error: patch failed, но проблема не решалась, т.к. при работе с гитом проблему нужно решать сверху вниз, а не наоборот, поэтому сначала разобрался с trailing whitespace, кому интересно читайте информацию о core.whitespace, вот кратко:
Git заранее настроен на обнаружение и исправление некоторых проблем, связанных с пробелами. Он может находить четыре основные проблемы с пробелами — две из них по умолчанию отслеживаются, но могут быть выключены, и две по умолчанию не отслеживаются, но их можно включить.
Решение проблемы очень простое:
git apply —whitespace=fix /dir/my.patch
таким образом мы говорим git-у пофиксить все проблемы связанные с пробелами и применить патч.
git apply patch
Создал патч, решил его накатить:
git apply /home/my.patch
и получил ошибку:
error: patch failed: fancytree/MIT-License.txt:4
error: fancytree/MIT-License.txt: patch does not apply
проблема решилась откатыванием всех изменений, с помощью команды:
git clean -fdx
после чего я снова попробовал накатить патч и все получилось.
git error: Untracked working tree file
В моем случае ошибка возникала, т.к. origin master был старее, чем мой master. Предположительно проблема возникла, т.к. ведущий прогер просто откатил главную ветку назад. Решение: посмотрите кол-во коммитов на которые Ваша ветка опережает origin master и откатитесь назад, как это сделал ведущий прогер, например он откатился на 5 коммитов назад и Вы так же сделайте.
Сабмодули
Решил обновить список сабмодулей:
git submodule update
получил ошибку:
No submodule mapping found in .gitmodules for path ‘vendor/hwi/oauth-bundle/HWI/Bundle/OAuthBundle’
решение:
git rm —cached vendor/hwi/oauth-bundle/HWI/Bundle/OAuthBundle
Git не добавляет содержимое директории
Опять же, дело в том, что эта директория является сабмодулем и git про это знает, поэтому выполняем команды:
mv vendor/yapro/lib/.git /tmp
git rm —cached vendor/yapro/lib/ -f
теперь git увидит все, что есть в директории vendor/yapro/lib/
18.09.2013 11:09