Unable to pull when changes are present on your branch как исправить

Hi i need some help with GitHub Desktop

Hi. I’ve just installed GitHub Desktop to work in a game jam but I’ve got some problems. I can’t pull the changes. When I’m trying it says “Unable to pull when changes are present on your branch. The following files would be overwritten”

Do someone know how to fix this??

Before using reset think about using revert so you can always go back.

https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert

On request

Source: https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert

git reset vs git revert
  sonic0002        2019-02-02 08:26:39 

When maintaining code using version control systems such as git, it is unavoidable that we need to rollback some wrong commits either due to bugs or temp code revert. In this case, rookie developers would be very nervous because they may get lost on what they should do to rollback their changes without affecting others, but to veteran developers, this is their routine work and they can show you different ways of doing that.
In this post, we will introduce two major ones used frequently by developers.

  • git reset
  • git revert

What are their differences and corresponding use cases? We will discuss them in detail below.
git reset
Assuming we have below few commits.
enter image description here

Commit A and B are working commits, but commit C and D are bad commits. Now we want to rollback to commit B and drop commit C and D. Currently HEAD is pointing to commit D 5lk4er, we just need to point HEAD to commit B a0fvf8 to achieve what we want. 
It’s easy to use git reset command.

git reset --hard a0fvf8

After executing above command, the HEAD will point to commit B.
enter image description here

But now the remote origin still has HEAD point to commit D, if we directly use git push to push the changes, it will not update the remote repo, we need to add a -f option to force pushing the changes.

git push -f

The drawback of this method is that all the commits after HEAD will be gone once the reset is done. In case one day we found that some of the commits ate good ones and want to keep them, it is too late. Because of this, many companies forbid to use this method to rollback changes.

git revert
The use of git revert is to create a new commit which reverts a previous commit. The HEAD will point to the new reverting commit. 
For the example of git reset above, what we need to do is just reverting commit D and then reverting commit C. 

git revert 5lk4er
git revert 76sdeb

Now it creates two new commit D’ and C’, 
enter image description here

In above example, we have only two commits to revert, so we can revert one by one. But what if there are lots of commits to revert? We can revert a range indeed.

git revert OLDER_COMMIT^..NEWER_COMMIT

This method would not have the disadvantage of git reset, it would point HEAD to newly created reverting commit and it is ok to directly push the changes to remote without using the -f option.
Now let’s take a look at a more difficult example. Assuming we have three commits but the bad commit is the second commit. 
enter image description here

It’s not a good idea to use git reset to rollback the commit B since we need to keep commit C as it is a good commit. Now we can revert commit C and B and then use cherry-pick to commit C again. 
enter image description here

From above explanation, we can find out that the biggest difference between git reset and git revert is that git reset will reset the state of the branch to a previous state by dropping all the changes post the desired commit while git revert will reset to a previous state by creating new reverting commits and keep the original commits. It’s recommended to use git revert instead of git reset in enterprise environment. 
Reference: https://kknews.cc/news/4najez2.html

Github is mostly used by developers for version control and collaborating with other developers on the same project. There are many functionalities provided by the Github like you can keep track of the changes made by you and also keep backups for the previous changes. However, sometimes you can get the error after committing to the Github repository like “ please commit your changes or stash them before you merge“.

In this entire tutorial you will learn how to solve the please commit your changes or stash them before you merge error.

Why does the please commit your changes or stash Error come?

Most of cases the error Please, commit your changes or stash them before you can merge comes when you have made any changes to the local machine. After that, you must have pushed the changes to the Github remote repository. Now if anyone will pull all the changes from the remote then they will get the error.

git pull

Output

error: Your local changes to the following files would be overwritten by merge:;
Please, commit your changes or stash them before you can merge.

How to solve the commit your changes Error?

One of the best solutions to solve this ” please commit your changes or stash them before you merge” error is to not merge with the local modifications as Github is protecting you from unwanted changes in your code.

You can follow the below steps to solve this error.

Step 1: Commit the changes

The first step is to commit to any changes you have made inside the project directory. To commit run the below command.

git commit -m "Your message"

Step 2: Store your changes temporary

After step one now you have to store all the changes in the stack.

git stash

Step 3: Pull the code from the remote repository

After stacking the changes, pull the files from the remote. To do so run the below command.

git pull <remote name> <remote branch name> (or) switch branch

Step 4: Pop the changes

The last step is to pop all the changes that were saved inside the stack.

Run the below bash command to pop.

git stash pop

Now you can commit the changes and push them to the remote repository. You will not get the error “please commit your changes or stash them before you merge” when you will pull the changes again in your local repository.

Conclusion

The error please commit your changes before you merge mainly comes when there are conflicts between the local and remote repository. If you are getting this error then you can solve it using the above steps.

I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Как игнорировать следующее сообщение об ошибке на git pull?

ваши локальные изменения в следующих файлах будут перезаписаны merge

что если я хочу перезаписать их?

Я пробовал такие вещи, как git pull -f, но ничего не работает.

чтобы быть ясным, я хочу только перезаписать определенные изменения, а не все.

25 ответов


если вы хотите удалить все локальные изменения из рабочей копии, просто спрячьте их:

git stash save --keep-index

если они вам больше не нужны, теперь вы можете бросить эту заначку:

git stash drop

если вы хотите перезаписать только определенные части ваших локальных изменений, есть две возможности:

  1. зафиксируйте все, что вы не хотите перезаписывать, и используйте метод выше для остальных.
  2. использовать git checkout path/to/file/to/revert для изменения, которые вы хотите перезаписать. Делать уверен, что файл не находится в стадии через git reset HEAD path/to/file/to/revert.

312

автор: Daniel Hilgarth


хорошо с помощью двух других ответов я придумал прямое решение:

git checkout HEAD^ file/to/overwrite
git pull

это работает для меня, чтобы переопределить все локальные изменения и не требует идентификации:

git reset --hard
git pull

вот решение, которое отбрасывает поэтапные изменения:

git reset file/to/overwrite
git checkout file/to/overwrite

вы можете либо зафиксировать изменения перед слиянием, либо сохранить их:

  1. git stash save
  2. git merge origin/master
  3. git stash pop

мое решение для решения этой проблемы было:

git checkout -- <file>

тогда я мог бы перезаписать файл через:

git pull

если ваш репозиторий содержит несколько файлов, которые удаляются из master:

  1. git checkout master
  2. git fetch origin
  3. git reset --hard origin/master
  4. git checkout -b newbranch

в недавнем Git вы можете добавить -r/--rebase on pull команда для перебазирования текущей ветви поверх восходящей ветви после извлечения. Предупреждение должно исчезнуть, но есть риск, что вы получите некоторые конфликты, которые вам необходимо решить.


в качестве альтернативы вы можете проверить другую ветку с силой, а затем вернуться к master снова, например:

git checkout origin/master -f
git checkout master -f

затем потяните его снова, как обычно:

git pull origin master

использование этого метода может сэкономьте время от тайника (git stash) и потенциальные проблемы с разрешениями, сброс файлов (git reset HEAD --hard), удаление (git clean -fd) и т. д. Кроме того, выше это легче запомнить.


эта проблема заключается в том, что вы внесли изменения локально в файл / s и тот же файл/S существует с изменениями в репозитории Git, поэтому перед pull / push вам понадобятся локальные изменения stash:

для перезаписи локальных изменений одного файла:

git reset file/to/overwrite
git checkout file/to/overwrite

заменить все локальные изменения (изменения во всех файлах):

git stash
git pull
git stash pop

также эта проблема может быть из-за того, что вы находитесь на ветке, которая не объединена с главной веткой.


иногда ничего из этого не работает. Досадно, из-за вещи LF я думаю, что будет работать удаление файлы затем потянуть. Не то чтобы я рекомендовал это решение, но если файл не существует, git не будет бесполезно сообщать вам, что ваши изменения (которые могут даже не быть изменениями) будут переопределены и позволят вам продолжить.

используйте на свой страх и риск.


вы можете использовать это для перезаписи файла

git checkout file_to_overwrite

Если вы хотите перезаписать определенные изменения, вам нужно каким-то образом сказать ему, какие из них вы хотите забыть.

вы можете попробовать выборочно хранить изменения, которые вы хотите отказаться от использования git stash --patch и затем бросив эту заначку с git stash drop. Затем вы можете вытащить удаленные изменения и объединить их как обычно.


лучший способ решить эту проблему:

git checkout -- <path/file_name>

после этого вы можете перезаписать файл с:

git pull origin master

3

автор: A H M Forhadul Islam


У меня был особый случай этого: у меня был файл с —assume-unchanged на нем. Его было трудно обнаружить, так как git status команда не показывала никаких изменений


это сработало для меня, чтобы отбросить изменения на живом удаленном сервере и вытащить из системы управления версиями GitHub:

git reset --hard
git pull origin master

Если вы хотите сохранить изменения на сервере, просто сливаются в новый элемент конфигурации. Метод обработки выглядит следующим образом:

git stash
git pull
git stash pop

возможно, вы не выполняете все операции. Ты знаешь, что делать дальше.


git stash save --keep-index не работал для меня.

ниже команда работает, как ожидалось.

git reset --hard
git pull

он переопределяет все локальные изменения, если они вам не нужны.


я игнорировал файл в моем РЕПО, и когда я это сделал git pull upstream master Я получил следующую ошибку:

ошибка: локальные изменения в следующие файлы будут переписаны слияния:
myfile.Яш
Пожалуйста, зафиксируйте свои изменения или спрячьте их, прежде чем вы сможете объединить.
Аборт

чтобы решить это, я сделал следующее

git update-index --no-assume-unchanged myfile.js

Я git status и

на ветке master ваша ветка позади «origin / master» на 4 коммита,
и можно быстро перемотать. (используйте «git pull» для обновления локального
бранч)

изменения, не поставленные для фиксации: (используйте » git add …» обновлять
что будет совершено) (используйте «git checkout — …» отбрасывать
изменения в рабочем каталоге)

изменено: myfile.js

никаких изменений для фиксации (используйте» git add «и/или»git commit-a»)

тогда я сделал git checkout myfile.js следовал по git pull upstream master. Эта пора операция git pull была успешной.


вот моя стратегия решения проблемы.

Постановка Задачи

нужно внести изменения в более чем 10 файлов. Мы пытались!—0—>, но мерзавец крикнул:

ошибка: локальные изменения в следующие файлы будут переписаны
путем слияния: пожалуйста, зафиксируйте свои изменения или спрячьте их, прежде чем сможете
объединить.

мы пытались выполнить commit а то pull, но они не работают любой.

решение

мы были в грязный этап на самом деле, потому что файлы были в «промежуточной области» a.к.»индексная область» и некоторые из них находились в «головной области» a.к.»локальный каталог Git». И мы хотели забрать изменения с сервера.

проверьте эту ссылку для получения информации о различных этапах Git в ясной форме: этапы GIT

мы следовали следующему шаги

  • git stash (это сделало наш рабочий каталог чистым. Ваши изменения хранятся в стеке Git).
  • git pull origin master (вытащите изменения с сервера)
  • git stash apply (применены все изменения из стека)
  • git commit -m 'message' (внесенные изменения)
  • git push origin master (передвинул изменения на сервер)
  • git stash drop (падение стека)

давайте поймем, когда и почему вам нужно тайник

если вы находитесь в грязный состояние, означает, что вы вносите изменения в свои файлы, а затем вы вынуждены, по любой причине,тянуть или переключатель в другой филиал для очень срочной работы, поэтому в этот момент Вы не можете тянуть или переключаться, пока не совершите изменение. The stash команда здесь как Рука помощи.

из книги ProGIT, 2-е издание:

часто, когда вы работаете над частью своего проекта, все в
грязное состояние, и вы хотите немного переключить ветви, чтобы работать
что-то еще. Проблема в том, что вы не хотите делать фиксацию
наполовину законченная работа, чтобы вы могли вернуться к этому позже. Этот
ответом на эту проблему является команда git stash. Припрятать берет
грязное состояние вашего рабочего каталога, то есть измененные отслеживаемые
файлы и поэтапные изменения-и сохраняет его в стопке незавершенных
изменения, которые можно применить в любое время.


Я столкнулся с этим при вытягивании из Мастера.

Как я справился с этим, используя Visual Studio;

  1. во-первых, я выполнил отмену фиксации на моем решении.
  2. затем я сделал процесс git pull.

надеюсь, что это помогает!


Если эта ошибка из-за окончания строк,

git add
git checkout mybranch

будет работать. Я не совсем понимаю, почему это работает.


для Pycharm вы можете сделать Git— > Revert, а затем потянуть.


это сообщение также может произойти, если git-lfs используется, и указатель файла был перезаписан реальным файлом.

затем вы можете использовать:

git stash
git lfs migrate import
git pull

полный выход из моего дела

λ git stash
Saved working directory and index state WIP on master: 5d4ad47 Merge branch 'feature/...' into 'master'
Encountered 1 file(s) that should have been pointers, but weren't:
        public/apple-touch-icon.png

λ git pull
Updating 5a4ad44..b25f79d
error: Your local changes to the following files would be overwritten by merge:
        public/apple-touch-icon.png
Please commit your changes or stash them before you merge.
Aborting

λ git lfs migrate import
migrate: Fetching remote refs: ..., done
migrate: Sorting commits: ..., done
migrate: Rewriting commits: 100% (0/0), done
migrate: Updating refs: ..., done
migrate: checkout: ..., done


λ git pull
Updating 5d4ad47..a25c79a
Fast-forward
 public/apple-touch-icon.png | Bin 2092 -> 130 bytes
 public/favicon.ico          | Bin 6518 -> 1150 bytes
 2 files changed, 0 insertions(+), 0 deletions(-)

см.https://github.com/git-lfs/git-lfs/issues/2839


Я пробовал, и это успешно, прежде чем тянуть, пусть зафиксировать все файлы, которые вы не зафиксировали, тогда вы не получите эти сообщения от AS.


git reset --hard && git clean -df

это сбросит и удалит все неотслеженные файлы.



Я сделал некоторые обновления на своем локальном компьютере, перенес их в удаленный репозиторий, и теперь я пытаюсь вытащить изменения на сервер, и я получаю сообщение;

ошибка: ваши локальные изменения в следующих файлах будут перезаписаны слиянием:

WP-содержание / W3TC-конфигурации / master.php

Пожалуйста, передайте свои изменения или спрячьте их, прежде чем сможете объединить.

Итак, я побежал,

git checkout -- wp-content/w3tc-config/master.php

и попробовал еще раз, и я получил то же сообщение. Я предполагаю, что что-то w3tcизменилось в файле конфигурации на сервере. Мне все равно, идет ли локальная копия или удаленная копия на сервер (я думаю, что удаленная копия лучше всего), я просто хочу иметь возможность объединить остальные мои изменения (обновления плагинов).

Любые идеи?



Ответы:


Вы не можете объединиться с локальными изменениями. Git защищает вас от потери потенциально важных изменений.

У вас есть три варианта:

  • Зафиксируйте изменения, используя

    git commit -m "My message"
    
  • Спрятать это.

    Шкатулка действует как стек, где вы можете помещать изменения и извлекать их в обратном порядке.

    Чтобы спрятать, введите

    git stash
    

    Сделайте слияние, а затем вытяните тайник:

    git stash pop
    
  • Откажитесь от локальных изменений

    используя git reset --hard
    илиgit checkout -t -f remote/branch

    Или: отменить локальные изменения для определенного файла

    с помощью git checkout filename







git stash
git pull <remote name> <remote branch name> (or) switch branch
git stash apply --index

Первая команда временно сохраняет ваши изменения в тайнике и удаляет их из рабочего каталога.

Вторая команда переключает ветви.

Третья команда восстанавливает изменения, которые вы сохранили в тайнике (эта --indexопция полезна, чтобы убедиться, что промежуточные файлы все еще находятся в стадии подготовки ).




Вы можете попробовать один из следующих методов:

перебазироваться

Для простых изменений попробуйте перебазировать поверх него, потянув за изменения, например:

git pull origin master -r

Таким образом, он будет применять вашу текущую ветку к верхней ветке после загрузки.

Это эквивалентно: checkout master, fetchи rebase origin/masterкоманда Git.

Это потенциально опасный режим работы. Он переписывает историю, которая не сулит ничего хорошего, когда вы уже опубликовали эту историю. Не используйте эту опцию, если вы не прочитали git-rebase(1)внимательно.


проверять, выписываться

Если вас не волнуют ваши локальные изменения, вы можете переключиться на другую ветку временно (с применением силы) и переключить ее обратно, например,

git checkout origin/master -f
git checkout master -f

сброс

Если вас не волнуют ваши локальные изменения, попробуйте сбросить его в HEAD (исходное состояние), например

git reset HEAD --hard

Если вышеупомянутое не поможет, это могут быть правила в вашем файле нормализации git ( .gitattributes), поэтому лучше зафиксировать то, что он говорит. Или ваша файловая система не поддерживает разрешения, поэтому вы должны отключить ее filemodeв своем git config.

Связанный: Как заставить «git pull» перезаписать локальные файлы?





Попробуй это

git stash save ""

и попробуйте снова потянуть



Итак, ситуация, с которой я столкнулся, была следующей:

ошибка: Ваши локальные изменения в следующих файлах будут перезаписаны слиянием: wp-content / w3tc-config / master.php Пожалуйста, передайте свои изменения или сохраните их перед тем, как объединить.

кроме, прямо перед этим, был удаленным: так на самом деле это:

remote: error: Ваши локальные изменения в следующих файлах будут перезаписаны слиянием: some / file.ext Пожалуйста, передайте свои изменения или сохраните их перед тем, как объединить.

То, что происходило, было (я думаю, не на 100% положительным), крюк получения git post начал работать и облажаться из-за изменений движения в репозитории удаленного сервера, которые теоретически не должны были быть затронуты.

Так что я закончил тем, что проследил через ловушку post-receive и обнаружил это: мне пришлось перейти в удаленный репозиторий на сервере, и произошло изменение (которого не было в моем локальном репозитории, который, на самом деле, сказал, что он совпадает, никаких изменений, ничего для фиксации, обновлений и т. д.) Так что пока на локальном сервере не было никаких изменений, на сервере я затем сделал, git checkout -- some/file.extа затем локальные и удаленные репозитории действительно совпали, и я смог продолжить работу и развернуть. Не совсем уверен, как возникла эта ситуация, хотя пара дюжин разработчиков плюс изменения в ИТ могут быть как-то связаны с этим.




ВНИМАНИЕ: Это удалит неотслеживаемые файлы, поэтому это не лучший ответ на этот вопрос.

В моем случае я не хотел хранить файлы, так что это сработало для меня:

Git 2.11 и новее:

git clean  -d  -fx .

Старый Git:

git clean  -d  -fx ""

Ссылка: http://www.kernel.org/pub/software/scm/git/docs/git-clean.html

  • -x означает, что игнорируемые файлы также удаляются, а также файлы, неизвестные git.

  • -d означает удаление неотслеживаемых каталогов в дополнение к неотслеживаемым файлам.

  • -f требуется, чтобы заставить его работать.


Чтобы сохранить записи о вновь созданных файлах при решении этой проблемы:

Если у вас есть недавно созданные файлы , вы можете создать исправление локальных изменений, извлечь удаленные слияния и применить локальное исправление после завершения удаленного слияния, как описано ниже, шаг за шагом:

  1. Поставь свои локальные изменения. (не совершать). Постановка необходима для создания патча новых созданных файлов (так как они все еще не отслежены)

git add .

  1. Создать патч для записи

git diff --cached > mypatch.patch

  1. Отменить локальные изменения и удалить новые локальные файлы

git reset --hard

  1. Вытащить изменения

git pull

  1. Примените свой патч

git apply mypatch.patch

Git объединяет изменения и создает файлы .rej для изменений, которые не объединяются.

По предложению Anu, если у вас есть проблемы с применением патча, попробуйте:

git apply --reject --whitespace=fix mypatch.patch
Этот ответ git: patch не применяется, подробно рассказывает об этой проблеме

Наслаждайтесь продолжением работы над своей функцией и вносите локальные изменения, когда закончите.





Просить совершить, прежде чем тянуть

  • мерзавец
  • git pull origin << фирменное имя >>

Если нужно :

  • Git Stash применить


Для меня только git reset --hardсработало.

Фиксация не была вариантом, так как нечего было коммитить.

Прятаться было не вариант, потому что нечего было прятать.

Похоже, это могло быть из исключенных файлов .git/info/excludeи с git update-index --assume-unchanged <file>некоторыми файлами.


В моем случае я сделал резервную копию, а затем удалил файл, на который Git жаловался, зафиксировал его, затем смог наконец проверить другую ветку.

Затем я заменил файл, скопировал обратно содержимое и продолжил, как будто ничего не произошло.



Я попробовал первый ответ: git stashс наибольшим количеством очков, но сообщение об ошибке все еще выскакивало, и затем я обнаружил, что эта статья фиксирует изменения вместо тайника «Reluctant Commit»

и сообщение об ошибке исчезло окончательно:

1: git add .

2: git commit -m "this is an additional commit"

3: git checkout the-other-file-name

тогда это сработало. надеюсь, этот ответ поможет. :)


Если вы используете Git Extensions, вы сможете найти свои локальные изменения, Working directoryкак показано ниже:

введите описание изображения здесь

Если вы не видите никаких изменений, возможно, это из-за неправильного субмодуля. Так что проверьте все предметы со значком подводной лодки, как показано ниже:

введите описание изображения здесь

Когда вы нашли какое-то незафиксированное изменение:

Выберите строку с помощью Working directory, перейдите на вкладку « Разница », щелкните правой кнопкой мыши строки с карандашом (или +или -), выберите « Сброс», чтобы сначала зафиксировать или зафиксировать или сохранить, или все, что вы хотите с ним сделать.


Для меня это сработало:

git reset --hard

а потом

git pull origin <*current branch>

после того

git checkout <*branch>


Вероятно

git --rebase --autostash

помог бы

The error message “Your local changes to the following files will be overwritten by merge” occurs in Git version control mechanism. This error occurs if you have modified a file which also has modifications in the remote repository.

Git Error: Your local changes to the following files will be overwritten by merge while coding

Git Error: Your local changes to the following files will be overwritten by merge

This error message is avoided IF there are no uncommitted files that also have modifications in the remote repository. When experiencing this message, it is best to consult your other team members and ask for their opinion. Whether you want to merge your local changes or keep the version present in the repository, it is best to keep everyone on board.

What are repositories? What are push and pull in Git?

A repository is a kind of storage for code which is constantly modified and obtained by team members through the GitHub version control mechanism. A ‘Pull’ means that you are pulling the latest version of the repository onto your local storage/IDE (Integrated Development Environment) such as Pycharm etc.

After a Pull, you make changes to the code or add more features. Once you are done, you ‘Push’ the code onto the repository so changes are saved and additions are made. The code gets accessible to other people as well.

If you are new to Github version control, it is recommended that you go through all the basics first. In this article, we assume that you already have basic knowledge and know all the ins and outs.

The resolution of this error message depends on what you want to do. You can discard your local changes and pull the ones in the repository or you can save your local changes into a stash and pull the version from the repository. It all depends on your preference.

Hence, we recommend that you consult with your team members and make sure that you all are on the same page before moving forward. If you commit wrongly or push the wrong version, it could affect the entire team.

Method 1: Forcing a pull to overwrite local changes

If you don’t care about the changes done locally and want to obtain the code from the repository, you can force a pull. This will overwrite all the local changes done on your computer a duplicate copy of the version in the repository will appear.

Execute the following commands in your IDE:

git reset -- hard

git pull

This will instantly destroy all your local changes so make sure that you know what you are doing and don’t need your local changes.

Method 2: Keeping both changes (local and from the repo)

If you want to keep both changes (changes done locally and changes present in the repository), you can add and commit your changes. When you pull, there will obviously be a merge conflict. Here you can use the tools in your IDE (such as Difftool and mergetool) to compare the two pieces of code and determine which changes to keep and which to remove. This is the middle way; no changes will be lost until you manually remove them.

git add $the_file_under_error

git commit

git pull

When you get a merge conflict, pop those conflict resolving tools and check line by line.

Method 3: Keeping both changes BUT not committing

This situation happens from time to time where developers are not ready to commit because there is some partly broken code which you are debugging. Here we can stash the changes safely, pull the version from the repository, and then unstash your code.

git stash save --keep-index

or

git stash
git pull

git stash pop

If there are some conflicts after you pop the stash, you should resolve them in the usual way. You can also use the command:

git stash apply

instead of pop if you are not ready to lose the stashed code due to conflicts.

If merge doesn’t seem like a viable option for you, consider doing a rebase. Rebasing is the process of moving or combining a sequence of commits to a new base commit. In the case of rebasing, change the code to:

git stash

git pull --rebase origin master

git stash pop

Method 4: Make changes to ‘specific’ parts of your code

If you want to make changes to specific parts of the code and don’t want to replace everything, you can commit everything that you don’t want to overwrite and then follow method 3. You can use the following command for the changes which you want to overwrite from the version present in the repository:

git checkout path/to/file/to/revert

or

git checkout HEAD^ path/to/file/to/revert

Also, you need to make sure that the file is not staged via:

git reset HEAD path/to/file/to/revert

Then proceed with the pull command:

git pull

This will then attempt at fetching the version from the repository.

Photo of Kevin Arrows

Kevin Arrows

Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.

The problem

Git desktop (and git bash) will leave the workspaces in an inconsistent state after failing to change a locked file.
The user then is told they have a bunch files that they have changed both in untracked and “not staged for commit”
The user gets confused because they didn’t have any changes prior to this and can panic into either deleting there work and making that delete into a new commit (destroying other peoples work) or adding/committing work that is already in the main branch.

Release version

3.0.3 x64

Operating system

Windows 10

Steps to reproduce the behavior

Our company hit this problem with a binary file (type: PDF) that was checked into the repo. It was NOT lfs tracked.
The user had main branch of repo checked out and no changes in staging or working spaces.
The user had “Adobe Reader DC” open and has that PDF file mentioned above open in the background.
Another user changes unrelated files (.py, .csv, etc) in the same repo, commits & pushes those to main branch.
Another user modifies the same PDF, commits/pushes to master…

The original user selects pull from Github desktop (they still have the PDF open in the background)
Github desktop fails with an error that says… Unable to pull when changes are present on your branch. The following files would be overwritten

The user is now faced with a bunch of file changes they did not make. (upon careful inspection these “changed” files account for the other users commits. Yet they look like changes.

The user is still at there original commit point prior to doing a git pull. So they don’t see commits in their history, which makes sense as those commits are the reason for all the now modified files.

If you setup the same scenario above, but you use git bash you see this error and are prompted with y/n

 git pull origin main
From https://github.******
Unlink of file 'REDACTED/02REDACTED/REDACTED/REDACTED.pdf' failed. Should I try again? (y/n) y
Unlink of file 'REDACTED/02REDACTED/REDACTED/REDACTED.pdf' failed. Should I try again? (y/n) n
error: unable to unlink old 'REDACTED/02REDACTED/REDACTED/REDACTED.pdf.pdf': Invalid argument
Updating files: 100% (31/31), done.
Updating 120ea68..13eb04a

the outcome is the same when you do a git status with git bash. You see all the future commit changes in your workspaces (staged, working) as if you made changes to them.

Very confusing for users.

Log files

No response

Screenshots

No response

Additional context

No response

  • honor8

Как правильно сделать слияние чужих и своих изменений?

работаем вдвоем над одним проектом, я поработал и хочу закоммитить изменения в репозиторий, перед этим делаю git pull и получаю

error: Your local changes to the following files would be overwritten by merge:
	1.php
	2.php
       3.php
Please, commit your changes or stash them before you can merge.
Aborting

т. е  в этим файлах у меня свои наработки,  и второй прогер уже закинул в репозиторий свои изменения,  вопрос.
Как мне его изменения слить и так чтобы не потерять свои изменения?  Вообщем как мне правильно все сделать и закоммитить


  • Вопрос задан

    более трёх лет назад

  • 15325 просмотров

Пригласить эксперта

Please, commit your changes or stash them before you can merge.

Что в этой фразе не понятного?

Вариант 1. – Делаете коммит, а котом git pull и оно вам предложит смержить.
Вариант 2. – Делаете git stash (прячет все незакомиченые локальные изменения); затем git pull; затем git stash pop, а дальше мержите.

Вообще есть третий вариант (на будущее) – создаете локально еще одну ветку, в ней работаете, а потом делаете git pull в основной ветке (точнее в той, от которой вы отпочковались) и мержите с ней свою ветку. (опять же, можете сделать stash, затем “отпочковаться”, затем слить изменения с репозитория и потом stash pop в свою ветку, а затем мержитесь, когда надо, с той веткой, откуда отпочковались).

Тут у вас есть несколько проблем:
1. команда git pull это на самом деле алиас для git fetch + git merge
работает она так, сначала через git fetch получает новое состояние ветки из origin, а потом передает управление git merge, он в свою очередь если ваша ветка разошлась делает merge, если нет то делает fast forward как следствие могут появиться не нужные комиты вида "Merge branch "test" to "test""

По этому советую вместо git pull делать всегда git fetch, а потом смотреть git status а там уже либо git rebase origin/test либо git pull

2. так же как вам уже сказали выше у вас есть изменения в локальных файлах, в целом в этом нет ничего плохого, их можно либо спрятать через git stash либо сделать комит

хочу закоммитить изменения в репозиторий, перед этим делаю git pull

Вот не надо ничего делать, пока не закоммитил. Git просто таки предназначен, чтобы коммитить часто. Закоммитил – считай, сохранил навсегда, и уже не потеряешь

Вести совместную разработку в одной ветви – плохой тон.

  1. *git pull --rebase --autostash создаётся ветвь refs/stash.
  2. git status могут появиться файлы modified (changed & indexed) и both modified (conflicted).
  3. git stash drop отбросить ветвь refs/stash. Затем заняться конфликтами.


  • Показать ещё
    Загружается…

15 мая 2023, в 15:23

3000 руб./за проект

15 мая 2023, в 14:57

4000 руб./за проект

15 мая 2023, в 14:45

30000 руб./за проект

Минуточку внимания

Just as the message indicates, you have made some changes to a file and you did not commit those changes to your repository. Someone else has made changes to that same file and when you try to pull the latest revision from your remote repository, you will lose whatever local changes you made to your file due to being overwritten by the other’s changes.

If you want to keep the changes you have made, commit your changes to the repository before pulling and then try to merge: git merge origin/master. If you don’t care for those changes, you can discard them: git stash drop.

UPDATE:

To answer your question on keeping your change locally without committing to the repository…

Just stash everything that you’ve changed, pull all the new stuff, and then pop back out your stash, i.e.

git stash
git pull
git stash pop

Take note that on stash pop there will be conflicts in this case (the message had already made that very clear).

Resolving the conflict is easy if you know that what you want is your what you put in the stash, i.e. your local changes. You just use

git checkout --theirs -- Common.Dal.csproj

Добавить комментарий