amgit
Suppose you are working on a software project with one other person. You and your partner share a repository on GitHub; you have a local copy of the repo on your laptop, and your partner has a local copy on their laptop.
Initially, there is a file named README.md in the repo, your local copy, and your partner’s local copy; and all three versions are identical.
Now suppose you and your partner want to revise this file. There are several ways you might collaborate:
(1) Time sharing: You could talk to each other and agree that you will not edit the same file at the same time. Instead, one of you will edit the file in your local copy, push the change to the repo, and then tell your partner that you are done. The other partner will pull the modified file, make additional changes, and then push them back to the repo.
(2) Space sharing: You could work on separate files at the same time. Each of you could edit their own files, push changes to the repo, and pull the other partner’s changes from the repo.
(3) [NOT RECOMMENDED] Work in branches: Before you start making changes, you could create a branch, push changes to the branch, and then work on merging the branches in the future.
(4) [NOT RECOMMENDED] Work on the same files, in the same branch, at the same time.
For people who are relatively new to Git, working on relatively small projects, and working part time, we STRONGLY recommend choosing option (1) or (2).
People with more Git experience will try to make you feel bad about these options, and they will badger you into choosing option (3). Ignore them.
However, even if you intend to choose (1) or (2), you are likely to make a mistake at some point and accidentally choose (4). In that case, you are likely to encounter a merge conflict.
What is a merge conflict?
In this document, we use “merge conflict” to refer to any scenario where you and your partner have changed the same file and you need to reconcile your changes.
With Jupyter notebooks, in particular, you should be aware that running a notebook generally modifies the contents, which can cause a merge conflict.
We’ll consider two scenarios, depending on whether the change you have made has been committed.
Scenario I: Local change, not committed
Suppose your partner has modified README.md and pushed the change to the repo. In your local copy, you have also modified README.md, but you have not yet committed the change. Let’s see what happens, and what you can do to resolve it.
1) Clone a repo on GitHub to make a local copy. If you have a partner, have them clone a local copy, too.
2) Tell your partner to edit README.md , commit the change, and push it to the repo.
Or, if you are working alone, you can simulate the same effect by viewing the repo on GitHub, editing README.md , making a small change, and committing the change.
3) In your local copy, edit README.md and save the change but don’t commit it. If you run git status , you should see:
4) If you run git pull , you should see:
This is a merge conflict. There are several ways you might proceed, depending on what changes you and your partner have made.
A: If you don’t care about the changes you have made in your local copy, the easiest thing to do is delete the file that would be overwritten by the merge. Try this:
The git pull should succeed now: it should pull the modified version of README.md from the repo, along with any other changes that are in the repo but not in your local copy.
B: If you don’t care about the changes your partner made and you want to replace them with your changes, the easiest thing to do is upload your modified file to GitHub. View your repo in a web browser, navigate to the directory that contains the conflicted file, and press the “Upload files” button. Navigate to your modified file and upload it. Now delete your local copy of the file and git pull again.
B2: Again, if you don’t care about the changes your partner made and you want to replace them with your changes, you can
And then add README.md , commit and push.
C: If there are changes in both versions that you want to keep, the easiest thing to do is merge them by hand. You can do that by running
meld is a graphical program that compares files and makes it easy to merge changes from the two of them until you have what you want.
If you don’t already have it installed, run
Or use whatever text editor you like to move the changes you want to keep from README.md.mine to README.md .
Then add, commit, and push the merged version of README.md as usual.
Scenario II: Local change, committed
Suppose your partner has modified README.md and pushed the change to the repo. In your local copy, you have also modified README.md , and you have committed the change.
Let’s see what happens, and what you can do to reconcile it.
1) Clone a repo on GitHub to make a local copy. If you have a partner, have them clone a local copy, too.
2) Tell your partner to edit README.md , commit the change, and push it to the repo. Or, if you are working alone, you can simulate the same effect by viewing the repo on GitHub, editing README.md, making a small change, and committing the change.
3) In your local copy, edit README.md , save the change, and commit it. If you run git status, you should see:
4) Run git push . You should see
Before you can push your changes to the repo, you have to pull the changes from the repo, resolve any conflicts, and then push your changes back to the repo.
5) Run git pull . You should see
This is the first example we have seen that is really a merge conflict in the sense that Git is aware that there is a conflict. If you run git status, you should see
6) Edit README.md . You will see that Git has combined the changes from the repo and your local copy:
In this example, HEAD refers to the most recent commit in your local copy, and the long hexadecimal string refers to the commit in the repo.
You can use any text editor to edit this file and resolve the conflict as you see fit. Save the resolved file.
Now you should be able to add, commit, and push the resolved file.
7) As an alternative to Step 6, you can use git mergetool . First, configure git to use meld , rather than whatever inchoate beast from the depths it uses by default:
Then run git mergetool . You should see:
If you hit return, it should launch meld and show you three versions of your file. Edit until the local version is what you want, then add, commit, and push it.
How to Fix Git Stash Merge Conflicts
Git stash allows you to save a draft of your in-progress changes and revert your working directory back to a clean slate. If stashed changes are applied ontop of new commits or other in-progress changes, there’s a chance for merge conflicts to arise.
If stash fails with a merge conflict, the error message will tell you that “git stash needs merge” or something similar to the messages below:
Note: This guide is a companion document to the video above. Merge conflicts are easier to understand when understood visually, so I recommend watching the video first.
How to fix a git stash needs merge error
Apply the stash
Note: If you have un-staged changes in your working directory, ensure you stage them by running git add . before running git stash pop . If unstaged files have merge conflicts, Git will abort the stash operation. You’ll know this happened if the message you receive contains the phrase “error: Your local changes to the following files would be overwritten by merge”. You’ll know you’ve entered the merge workflow when you see this phrase: “CONFLICT (content): Merge conflict”.
When stash fails with a merge conflict note the file(s) that failed the merge. Open each of the failed files in a text editor of your choice and manually resolve the conflicts. After saving the files, stage them:
At this point, you’ve resolved the conflicts and can continue development; however, you may want to consider commiting your changes before moving on for future readabily.
Lastly, when git stash pop fails with merge conflicts, the stash entry isn’t removed from the stash list. After fixing the merge conflict, remove the stash entry by running:
Workarounds
If you’d rather not fix a merge conflict right away, you can pop you changes out onto a new branch instead of the branch on which the stash was created:
This will allow you to continue development on a separate branch, then use merge/rebase to bring those branched changes back onto mainline at your leasure.
Ошибки git «Your local changes to the following files would be overwritten by merge» и «Please commit your changes or stash them before you merge» (РЕШЕНО)
Чтобы синхронизировать (обновить) свой локальный репозиторий с удалённым, используется команда:
Но она может закончиться неудачей и вызвать следующую ошибку:
Суть ошибки в том, что на удалённом репозитории сделаны изменения, но они не могут быть приняты, поскольку в вашем локальном репозитории тоже сделаны изменения и в результате если будут приняты обновления, то ваши локальные данные потеряются.
Такое может произойти по разным причинам, например, вы чуть подправили файл, или вы подготовили изменения для отправки на удалённый репозиторий и отправили их (сделали commit), но эти изменения ещё не приняты. В любом из этих случаев вы столкнётесь с этой ошибкой.
В ошибке показан проблемный файл (в данном случае это data/cf-subnet.txt), для проверки, были изменения на удалённом репозитории или в вашем локальном репозитории, вы также можете использовать команду:
Она также покажет список не синхронизированных файлов.
Подсказка в ошибке предлагает сделать commit или stash.
Но вариантов исправить эту ошибку четыре.
1. Отправить изменения (сделать commit)
2. Сделать stash
Если вы не знаете, что такое stash, то stash это как стек, временное хранилище, куда вы можете отправить сделанные изменения, а затем вернуть их обратно.
Чтобы спрятать изменения, то есть сделать stash выполните:
Затем примите изменения из удалённого репозитория (git pull).
А затем верните свои изменения из stash:
Ну а если стек спрятанных изменений вам вовсе не нужен, то его удалить можно следующей командой:
3. Отменить локальные изменения
Чтобы сбросить изменения в локальном репозитории выполните команду:
4. Сбросить локальные изменения для определённого файла
Чтобы сделать это, используйте команду вида:
Заключение
Какой бы способ вы не выбрали, после любого из этих вариантов вы можете обновить свой локальный репозиторий до последней версии с помощью:
“brew update” fails with a merge error
![]()
It had been awhile since I had last updated my homebrew install, so I popped into the command line to run the trusty “brew update” command, but instead, I was greeted with this:
$ brew update
error: Your local changes to the following files would be overwritten by merge: README.mdPlease, commit your changes or stash them before you can merge.
Aborting Error: Failure while executing: git pull -q origin refs/heads/master:refs/remotes/origin/master
Well, crap, I have no idea what README.md file it’s talking about, or even the start of a hint of how to find it. Do I have to do some sort of search through my whole filesystem to find it? Can I narrow it down to my Cellar?
Or am I just an idiot? brew —prefix tells me the root directory for my homebrew install, and that’s also where the git repo for it lives. I solved the problem by doing the following:
$ cd `brew —prefix` #go to the git repo
$ git checkout — . #destroy all unstaged changes