Git pull error your local changes to the following files would be overwritten by merge

How do I ignore the following error message on Git pull? Your local changes to the following files would be overwritten by merge What if I want to overwrite them? I've tried things like git pu...

Here is my strategy to solve the problem.

Problem Statement

We need to make changes in more than 10 files. We tried PULL (git pull origin master), but Git shouted:

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

We tried to execute commit and then pull, but they didn’t work either.

Solution

We were in the dirty stage actually, because the files were in the «Staging Area» a.k.a «Index Area» and some were in the «Head Area» a.k.a «local Git directory». And we wanted to pull the changes from the server.

Check this link for information about different stages of Git in a clear manner: GIT Stages

We followed the following steps

  • git stash (this made our working directory clean. Your changes are stored on the stack by Git).
  • git pull origin master (Pull the changes from the server)
  • git stash apply (Applied all the changes from stack)
  • git commit -m 'message' (Committed the changes)
  • git push origin master (Pushed the changes to the server)
  • git stash drop (Drop the stack)

Let’s understand when and why you need stashing

If you are in the dirty state, means you are making changes in your files and then you are compelled, due to any reason, to pull or switch to another branch for some very urgent work, so at this point you can’t pull or switch until you commit your change. The stash command is here as a helping hand.

From the book ProGIT, 2nd Edition:

Often, when you’ve been working on part of your project, things are in
a messy state and you want to switch branches for a bit to work on
something else. The problem is, you don’t want to do a commit of
half-done work just so you can get back to this point later. The
answer to this issue is the git stash command. Stashing takes the
dirty state of your working directory – that is, your modified tracked
files and staged changes – and saves it on a stack of unfinished
changes that you can reapply at any time.

When working on a project with a team, you might stumble upon error messages like these when trying to perform a «git pull» in your repository:

error: Your local changes to the following files would be overwritten by merge: ...

-or-

error: Untracked working tree file 'images/icon.png' would be overwritten by merge

The reason for error messages like these is rather simple: you have local changes that would be overwritten by the incoming new changes that a «git pull» would bring in.

For obvious safety reasons, Git will never simply overwrite your changes. This also means that there is no «force pull» feature in Git — but we can of course perform a couple of steps to emulate such a command.

Step 1: Cleaning Up the Working Copy

First, you’ll need to make sure your working copy doesn’t contain these conflicting changes anymore. There are two ways to achieve this:

a) Saving Local Changes on a Stash

If you want to preserve your local changes, you can safely store them on a Stash. They will be available in case you want them back at a later point.

$ git stash --include-untracked

b) Discarding Local Changes

If you are sure that you don’t need them anymore, you can discard your local changes completely:

$ git reset --hard

If you also have untracked / new files, you will have to use the «git clean» command to get rid of these, too:

$ git clean -fd

Please be careful with these commands: discarding local changes and untracked files cannot be undone!

Step 2: Pull Again

After you have cleaned up any local changes / untracked files that would have been overwritten, the pull will finally work:

$ git pull

Auto-Stashing in Tower

If you’re using the Tower Git client, you’ll notice that it helps you avoid these situations: whenever you have uncommitted local changes present and want to perform an action like Pull, Checkout or Merge, Tower will automatically offer to store these changes safely on a Stash.

This way, you neither have to take any extra steps nor do you have to think about this anymore.

Learn More

  • Check out the chapter Integrating Remote Changes in our free online book
  • More frequently asked questions about Git & version control

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.

  • 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

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


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

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

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

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

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. Затем заняться конфликтами.


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

09 февр. 2023, в 22:06

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

09 февр. 2023, в 22:01

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

09 февр. 2023, в 22:00

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

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

  • MiniTool

  • MiniTool News Center

  • Fix Git Error — Your Local Changes Would Be Overwritten by Merge

By Daisy | Follow |
Last Updated August 31, 2022

google search

If you have modified files that also have modifications in the remote repository, you may receive the “your local changes to the following files would be overwritten by merge” error message. This post from MiniTool offers fixes.

What Is a Repository? What Is Push and Pull in Git?

What is a repository? A repository is a store of code that team members are constantly modifying and fetching through the GitHub version control mechanism.

«Pull» means that you pull the latest version of the repository to your local storage/IDE (Integrated Development Environment) such as Pycharm etc. After pulling, you can change the code or add more functionality. When you’re done, you «push» your code to the repository so your changes can be saved and added. Others can also access the code.

How to Fix “Your Local Changes to the Following Files Would Be Overwritten by Merge”

Fix 1: Force a Pull to Overwrite Local Changes

The first method for you is to force a pull to overwrite local changes. This will overwrite any local changes done on your computer and a copy of the version in the repository will appear. You need to run the following commands in IDE.

  • git reset — hard
  • git pull

Then, you can check if the “error: your local changes to the following files would be overwritten by merge:” message has gone.

Fix 2: Keep Both Changes

If you want to keep both of these changes (the one done locally and the one in the repository), you can add and commit your changes. You need to execute the following codes in IDE:

  • git add $the_file_under_error
  • git commit
  • git pull

Fix 3: Keep Both Changes but Not Commit

It happens from time to time that the developer is not ready to commit because you are debugging some partially broken code. Here we can safely stash the changes, pull the version from the repository, and unstore your code.

  • git stash save —keep-index

or

  • git stash
  • git pull
  • git stash pop

If there are some conflicts after popping into the store, you should resolve them in the usual way. You can also use the following codes:

  • git stash apply

If merging is not a viable option for you, consider rebasing In the case of rebasing, change the code to

  • git stash
  • git pull —rebase origin master
  • git stash pop

Fix 4: Make Changes to Parts of Your Code

If you want to make changes to a specific part of the code and don’t want to replace everything, you can commit everything you don’t want to override and follow fix 3. You can use the following codes to make changes you want to override from the version that exists 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
  • git pull

Also see: Fix Git Error: You Need to Resolve Your Current Index First Now!

Final Words

These are common solutions to fix “your local changes would be overwritten by merge” in Git. If you have any other useful methods to remove this error, leave a comment below to let us know.

About The Author

Daisy

Position: Columnist

She was graduated from the major in English. She has been the MiniTool editor since she was graduated from university. She specializes in writing articles about backing up data & systems, cloning disks, and syncing files, etc. She is also good at writing articles about computer knowledge and computer issues. In daily life, she likes running and going to the amusement park with friends to play some exciting items.

Git Pull Force – How to Overwrite Local Changes With Git

When you learn to code, sooner or later you’ll also learn about Version Control Systems. And while there are many competing tools in this space, one of them is the de facto standard used by almost everyone in the industry. It’s so popular that there are companies that use its name in their branding. We’re talking about Git, of course.

While Git is a powerful tool, its power is well-hidden. There are some essential concepts that you need to understand to become really proficient with Git. The good news is that once you learn them, you’ll hardly ever run into trouble you can’t escape from.

The Typical Workflow

In a typical Git workflow you’ll use a local repository, a remote repository, and one or more branches. Repositories store all the information about the project, including its entire history and all the branches. A branch is basically a collection of changes leading from an empty project to the current state.

After cloning a repository, you work on your local copy and introduce new changes. Until you push local changes to the remote repository, all your work is available only on your machine.

When you finish a task, it’s time to synchronize with the remote repository. You want to pull the remote changes to keep up with the project’s progress, and you want to push the local changes to share your work with others.

All is well when you and the rest of your team are working on totally separate files. Whatever happens, you won’t be stepping on each other’s feet.

However, there are times when you and your teammates simultaneously introduce changes in the same place. And that’s usually where the problems begin.

Have you ever executed git pull only to see the dreaded error: Your local changes to the following files would be overwritten by merge:? Sooner or later, everyone runs into that problem.

What’s more confusing here is that you don’t want to merge anything, just pull, right? Actually, pull is a bit more complicated than you might have thought.

How Exactly does Git Pull Work?

Pull is not a single operation. It consists of fetching data from the remote server and then merging the changes with the local repository. These two operations can be performed manually if you want:

git fetch
git merge origin/$CURRENT_BRANCH

The origin/$CURRENT_BRANCH part means that:

  • Git will merge the changes from the remote repository named origin (the one you cloned from)
  • that have been added to the $CURRENT_BRANCH
  • that are not already present in your local checked out branch

Since Git only performs merges when there are no uncommitted changes, every time you run git pull with uncommitted changes could get you into trouble. Fortunately, there are ways to get out of trouble in one piece!

image-167

Photo by Sneaky Elbow / Unsplash

Different Approaches

When you have uncommitted local changes and still want to pull a new version from the remote server, your use case typically falls into one of the following scenarios. Either:

  • you don’t care about the local changes and want to overwrite them,
  • you care about the changes very much and would like to apply them after the remote changes,
  • you want to download the remote modifications but not apply them yet

Each of the approaches requires a different solution.

You Don’t Care About the Local Changes

In this case, you just want to drop all the uncommitted local changes. Perhaps you modified a file to experiment, but you no longer need the modification. All you care about is being up to date with the upstream.

This means that you add one more step between fetching the remote changes and merging them. This step will reset the branch to its unmodified state, thus allowing git merge to work.

git fetch
git reset --hard HEAD
git merge origin/$CURRENT_BRANCH

If you don’t want to type the branch name every time you run this command, Git has a nice shortcut pointing to the upstream branch: @{u}. An upstream branch is the branch in the remote repository that you push to and fetch from.

This is how the above commands would look like with the shortcut:

git fetch
git reset --hard HEAD
git merge '@{u}'

We are quoting the shortcut in the example to prevent the shell from interpreting it.

You Very Much Care About the Local Changes

When your uncommitted changes are significant to you, there are two options. You can commit them and then perform git pull, or you can stash them.

Stashing means putting the changes away for a moment to bring them back later. To be more precise, git stash creates a commit that is not visible on your current branch, but is still accessible by Git.

To bring back the changes saved in the last stash, you use the git stash pop command. After successfully applying the stashed changes, this command also removes the stash commit as it is no longer needed.

The workflow could then look like this:

git fetch
git stash
git merge '@{u}'
git stash pop

By default, the changes from the stash will become staged. If you want to unstage them, use the command git restore --staged (if using Git newer than 2.25.0).

You Just Want to Download the Remote Changes

The last scenario is a little different from the previous ones. Let’s say that you are in the middle of a very messy refactoring. Neither losing the changes nor stashing them is an option. Yet, you still want to have the remote changes available to run git diff against them.

As you have probably figured out, downloading the remote changes does not require git pull at all! git fetch is just enough.

One thing to note is that by default, git fetch will only bring you changes from the current branch. To get all the changes from all the branches, use git fetch --all. And if you’d like to clean up some of the branches that no longer exist in the remote repository, git fetch --all --prune will do the cleaning up!

image-166

Photo by Lenin Estrada / Unsplash

Some Automation

Have you heard of Git Config? It’s a file where Git stores all of the user-configured settings. It resides in your home directory: either as ~/.gitconfig or ~/.config/git/config. You can edit it to add some custom aliases that will be understood as Git commands.

For example, to have a shortcut equivalent to git diff --cached (that shows the difference between the current branch and the staged files), you’d add the following section:

[alias]
  dc = diff --cached

After that, you can run git dc whenever you wish to review the changes. Going this way, we can set up a few aliases related to the previous use cases.

[alias]
  pull_force = !"git fetch --all; git reset --hard HEAD; git merge @{u}"
  pf = pull_force
  pull_stash = !"git fetch --all; git stash; git merge @{u}; git stash pop"

This way, running git pull_force will overwrite the local changes, while git pull_stash will preserve them.

The Other Git Pull Force

Curious minds may have already discovered that there is such a thing as git pull --force. However, this is a very different beast to what’s presented in this article.

It may sound like something that would help us overwrite local changes. Instead, it lets us fetch the changes from one remote branch to a different local branch. git pull --force only modifies the behavior of the fetching part. It is therefore equivalent to git fetch --force.

Like git push, git fetch allows us to specify which local and remote branch do we want to operate on. git fetch origin/feature-1:my-feature will mean that the changes in the feature-1 branch from the remote repository will end up visible on the local branch my-feature. When such an operation modifies the existing history, it is not permitted by Git without an explicit --force parameter.

Just like git push --force allows overwriting remote branches, git fetch --force (or git pull --force) allows overwriting local branches. It is always used with source and destination branches mentioned as parameters. An alternative approach to overwriting local changes using git --pull force could be git pull --force "@{u}:HEAD".

Conclusion

The world of Git is vast. This article covered only one of the facets of repository maintenance: incorporating remote changes into a local repository. Even this everyday scenario required us to look slightly more in-depth into this version control tool’s internal mechanisms.

Learning actual use cases helps you better understand how Git works under the hood. This, in turn, will make you feel empowered whenever you get yourself into trouble. We all do that from time to time.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Ошибки 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. Сбросить локальные изменения для определённого файла

Чтобы сделать это, используйте команду вида:

Заключение

Какой бы способ вы не выбрали, после любого из этих вариантов вы можете обновить свой локальный репозиторий до последней версии с помощью:

Как игнорировать ошибку в «git pull» о моих локальных изменениях, которые будут перезаписаны слиянием?

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

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

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

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

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

25 ответов

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

на ветке 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.

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

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

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

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

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

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

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

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

vedro-compota's picture

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

Общий случай

Все просто — у вас незакомиченные изменения, а вы пытаетесь подтянуть новое состояние из удаленного репозитория, есть как минимум два вариант решения:

  1. или сделать коммит на этой машине (где наблюдается ошибка)
  2. или откатить изменения, если они вам не нужны

Если ошибка на сервере

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

Главная идея для сервера: на сервере файлы под контролем гит-а править не следует, это будет приводить к ошибкам вроде той, о которой сейчас говорим.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Git public key error
  • Git needs merge error you need to resolve your current index first
  • Git merge error the following untracked working tree files would be overwritten by merge
  • Git lfs smudge error
  • Git lfs error downloading object

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии