Error cannot pull with rebase you have unstaged changes error please commit or stash them

I have started collaborating with a few friends on a project & they use the heroku git repository. I cloned the repository a few days ago and they have since made some changes so I am trying t...

I have started collaborating with a few friends on a project & they use the heroku git repository.

I cloned the repository a few days ago and they have since made some changes so I am trying to get the latest updates

I ran the git pull --rebase command as stated here(Is this the right way to do it?): https://devcenter.heroku.com/articles/sharing#merging-code-changes

I get the following error:

$ git pull --rebase
Cannot pull with rebase: You have unstaged changes.
Please commit or stash them.

My guess is that I messed around with the code and now it wants me to either commit or discard(is that what does stash means?) the changes. Is this what is happening? If this is the case I would like to discard any changes I might have made and just get the updated code from the git repository.

Any idea of what I can do?

asked May 7, 2014 at 12:12

user3597950's user avatar

If you want to keep your working changes while performing a rebase, you can use --autostash. From the documentation:

Before starting rebase, stash local modifications away (see git-stash[1]) if needed, and apply the stash when done.

For example:

git pull --rebase --autostash

answered Apr 6, 2017 at 18:20

mkobit's user avatar

mkobitmkobit

42.2k12 gold badges152 silver badges147 bronze badges

8

Do git status, this will show you what files have changed. Since you stated that you don’t want to keep the changes you can do git checkout -- <file name> or git reset --hard to get rid of the changes.

For the most part, git will tell you what to do about changes. For example, your error message said to git stash your changes. This would be if you wanted to keep them. After pulling, you would then do git stash pop and your changes would be reapplied.

git status also has how to get rid of changes depending on if the file is staged for commit or not.

answered May 7, 2014 at 12:20

Schleis's user avatar

SchleisSchleis

40.1k7 gold badges67 silver badges87 bronze badges

5

Pulling with rebase is a good practice in general.

However you cannot do that if your index is not clean, i.e. you have made changes that have not been committed.

You can do this to work around, assuming you want to keep your changes:

  1. stash your changes with: git stash
  2. pull from master with rebase
  3. reapply the changes you stashed in (1) with: git stash apply stash@{0} or the simpler git stash pop

answered May 7, 2014 at 12:20

Kostas Rousis's user avatar

Kostas RousisKostas Rousis

5,8381 gold badge32 silver badges38 bronze badges

6

If you want to automatically stash your changes and unstash them for every rebase, you can do this:

git config --global rebase.autoStash true

answered Mar 26, 2020 at 22:40

agirault's user avatar

agiraultagirault

2,30019 silver badges24 bronze badges

1

First start with a
git status

See if you have any pending changes.
To discard them, run

note that you will lose your changes by running this

git reset --hard

ahmadali shafiee's user avatar

answered May 7, 2014 at 12:20

Igal S.'s user avatar

Igal S.Igal S.

12.4k4 gold badges31 silver badges47 bronze badges

2

This works for me:

git fetch
git rebase --autostash FETCH_HEAD

answered Nov 9, 2017 at 15:14

CppChase's user avatar

CppChaseCppChase

88212 silver badges25 bronze badges

2

You can always do

git fetch && git merge --ff-only origin/master

and you will either get (a) no change if you have uncommitted changes that conflict with upstream changes or (b) the same effect as stash/pull/apply: a rebase to put you on the latest changes from HEAD and your uncommitted changes left as is.

answered Jul 23, 2014 at 20:35

Jared Updike's user avatar

Jared UpdikeJared Updike

7,0478 gold badges45 silver badges70 bronze badges

When the unstaged change is because git is attempting to fix eol conventions on a file (as is always my case), no amount of stashing or checking-out or resetting will make it go away.

However, if the intent is really to rebase and ignore unstaged changed, then what I do is delete the branch locally then check it out again.

git checkout -f anyotherbranchthanthisone
git branch -D thebranchineedtorebase
git checkout thebranchineedtorebase

Voila! It hasn’t failed me yet.

phuclv's user avatar

phuclv

36k13 gold badges147 silver badges456 bronze badges

answered May 26, 2017 at 14:09

tggagne's user avatar

tggagnetggagne

2,8541 gold badge20 silver badges15 bronze badges

0

Follow the below steps

From feature/branch (enter the below command)

git checkout master

git pull

git checkout feature/branchname

git merge master

answered Oct 12, 2020 at 13:46

Thiru's user avatar

ThiruThiru

251 silver badge8 bronze badges

there you just need to restore the unstagged changes with this command below

for my case i had errors in yarn file for your case it can be another file

git restore —staged yarn.lock

answered Oct 22, 2021 at 8:17

Bukenya KizzaRoland's user avatar

Содержание

  1. Solution:Cannot pull with rebase: You have unstaged changes in Github
  2. Git: How to save your changes temporarily
  3. «Fixed». Please pull master.
  4. How to pull changes while having uncommitted changes?
  5. Automation with «rebase.autostash»
  6. Wrap up
  7. Ошибка: не может потянуть с rebase: у вас есть неустановленные изменения
  8. ОТВЕТЫ
  9. Ответ 1
  10. Ответ 2
  11. Ответ 3
  12. Ответ 4
  13. Ответ 5
  14. Ответ 6
  15. Mackup breaks oh-my-zsh upgrade #1384
  16. Comments
  17. Откуда это перебазирование?
  18. 2 ответа

Solution:Cannot pull with rebase: You have unstaged changes in Github

Git has a number of good features designed to improve user experience with Github and reduce the chances of data loss. Earlier I have explained about Solution: Github ‘Please tell me who you are’ error. Today I am going to explain about the common message which you might get when executing pull command.

Recently I was trying to run git pull –rebase command but I got message like

Git stash command is kind of commit stored changes to temporary space and clean working copy. Then your working copy will be reverted to HEAD.It is a good place to store uncommitted changes.

When you stash the changes, your changes will be stored in temporary space and your working copy will be reverted to HEAD

git pull –rebase is a good practice to use in general.This is very specific problem when you pull data from server so let’s check it with example

You have changes that have not been committed and you are going to pull changes from the server, you will get above error.This error says commit your local changes before you pull or stash changes mean store local changes to another place for temporary and get back with pop.

You can do this to work around using following steps

1. stash your changes with: git stash
2. pull from master with rebase: git pull –rebase
3. Then execute simpler git stash pop. With this command, it deletes that stash for good, while apply does not.

Here I have used git stash pop but After changes have been stashed, there are a few options of to get changes back to local:

1. git stash pop: This command takes a stashed change and removes changes from the stash stack and apply it to your current working tree.

2. git stash applies : This command takes a stashed change and applies it to your current working tree. You need to delete stash stack using git stash drop .

3. git stash branch: This command creates a new branch from the same commit you were on when you stashed the changes and applies the stashed changes to the new branch.

Experiment with the stash before using it on some really important work 🙂

Источник

Git: How to save your changes temporarily

«Fixed». Please pull master.

This scenario should be very familiar to you.

«You are coding an important feature.

Git status reveals a large number of uncommitted
changes.

As you test your feature, the app reports a nasty crash/bug/assertion on a
different module. As you are blocked from testing, you reach out to the owner.

The code owner informs you that he pushed a fix a few moments ago.»

If you have worked in a team environment, you should at least once experienced the scenario above.
I definitely have, especially working on a codebase with 1000 or more daily commits ( we use git as our version control ).

Well, what would you do? The most common step is to pull master to retrieve the fix.
So, you run back to your desk, and execute git pull —rebase .

I am a fan of git rebase. I think that using rebase makes git history so much cleaner and easier to maintain.

Instead of getting a list of file changes or commits, your terminal reports this error:

Exit fullscreen mode

Translation: «You still have work in progress and I don’t want to mess up and overwrite
your changes. Please commit or temporarily shelve your work.»

Since you have uncommitted changes, you can’t pull from master.
You could commit your changes and move on.

Emphasizing the word: commit — I personally think every commit should
be workable, compilable and maintainable code
( else I would rename git commit to git save )

Back to our problem — there is an easier way.

How to pull changes while having uncommitted changes?

Use Git Stash command.

Git Stash excels in these types of scenarios
(where you need to pull the latest code changes while not being ready to commit your
own changes).

git stash is a git command that allows you to temporarily shelve
or put aside uncommitted changes.
You are then free to update your local copy.
And can immediately continue where you left off by popping your stash.

Back to our scenario, I would execute git stash with:

Exit fullscreen mode

The -u sign is optional but I find it very handy. It tells git stash to include
new files ( git stash untracked files ).

Now you’re left with a clean working tree. Hopefully, git pull —rebase should be able
to work.
To continue where you left off, use git stash pop .

Exit fullscreen mode

This will pop the latest stash to your working directory.
And that’s it, you have successfully pulled master without committing your local changes
with just 3 commands.

  1. git stash -u
  2. git pull —rebase
  3. git stash pop

Automation with «rebase.autostash»

I don’t know about you but writing 3 commands every time does get tiring.

So, can «git pull» auto stash and pop pending changes? Yes.

You could create a special git alias that runs all 3 commands in order.

However, since Git version 2.7,
a new global config flag ( rebase.autostash ) was introduced that automates stashing. Amazing!

By default, this flag is set to false. Enable it globally by running:

Exit fullscreen mode

Now, whenever you run git pull —rebase , your local changes will automatically be stashed
and popped back. Pretty neat.

Wrap up

Git stash shines in scenarios when you’re stuck between pulling master
and having a dirty working copy
( especially during moments when your boss comes in and demands that you fix something immediately ).

Paired with rebase.autoStash , my daily git experience is smooth and easy.

Finally, I highly recommend visiting git-stash documentation page,
if you want to know more about the different modes of git stash.

Источник

Ошибка: не может потянуть с rebase: у вас есть неустановленные изменения

Я начал сотрудничать с несколькими друзьями в проекте, и они используют репозиторий heroku git.

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

Я запустил команду git pull —rebase , как указано здесь (это правильный способ сделать это?): https://devcenter.heroku.com/articles/sharing#merging-code-changes

Я получаю следующую ошибку:

Моя догадка заключается в том, что я испортил код и теперь он хочет, чтобы я либо совершал, либо отбрасывал (это то, что означает stash?) изменения. Это то, что происходит? Если это так, я хотел бы отказаться от любых изменений, которые я мог бы сделать, и просто получить обновленный код из репозитория git.

Любая идея, что я могу сделать?

ОТВЕТЫ

Ответ 1

Do git status , это покажет вам, какие файлы были изменены. Поскольку вы заявили, что не хотите сохранять изменения, вы можете сделать git checkout — или git reset —hard , чтобы избавиться от изменений.

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

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

Ответ 2

Вытягивание с помощью rebase является хорошей практикой в ​​целом.

Однако вы не можете этого сделать, если ваш индекс не чист, т.е. вы внесли изменения, которые не были зафиксированы.

Вы можете сделать это, чтобы работать, предполагая, что хотите сохранить свои изменения:

  • запишите свои изменения с помощью: git stash
  • вытащить из мастера с rebase
  • повторно примените изменения, которые вы спрятали в (1), с помощью: git stash apply [email protected]<0>или более простого git stash pop

Ответ 3

Сначала начните с git status

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

Ответ 4

Вы всегда можете сделать

и вы либо получите (a) никаких изменений, если у вас есть незафиксированные изменения, которые конфликтуют с изменениями восходящего потока или (б) тот же эффект, что и stash/pull/apply: rebase, чтобы поместить вас в последние изменения от HEAD и вашего незафиксированные изменения влево как есть.

Ответ 5

Если вы хотите сохранить свои рабочие изменения во время выполнения переустановки, вы можете использовать —autostash . Из документация:

Перед запуском rebase удалите локальные модификации (см. git -stash [1]), если необходимо, и примените тайник, когда сделал.

Ответ 6

Когда неустановленное изменение происходит из-за того, что git пытается исправить соглашения eol в файле (как всегда в моем случае), никакие блокировки или проверки или сброса не заставят его уйти.

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

Источник

Mackup breaks oh-my-zsh upgrade #1384

I’m using the iCould engine, no other configuration.

After running mackup backup -f , the

/.oh-my-zsh is left in a dirty state, which breaks upgrade_oh_my_zsh .

The text was updated successfully, but these errors were encountered:

I had this issue too. This happens when you add anything to the custom directory (with or without Mackup`).

All you have to do is the following in the terminal

Hope that helps!

The directory is being created by Mackup. When I git reset —hard origin/HEAD , running mackup always re-creates it.

Yes, since Mackup uses symbolic links there’s no other way I can think of to achieve this. Hopefully, my steps work for you, it’s a little bit of a pain but doesn’t take too long.

Yeah I’ve already been getting by by doing this. The ability to disable certain apps would be nice.

You can choose not to sync an application if you’d rather not deal with this issue and not backup oh-my-zsh with Mackup

Ah perfect, thanks 👍

@joshmedeski Isn’t the issue that Mackup creates symlinks that cannot be stashed?

This is the error I get when trying to stash my changes:

Do you have an idea on how I could solve this?

[edit]
I just resorted to resetting the repo as @ileitch suggested.

Then re-installed my custom plugins and ran mackup backup -f

Isn’t the issue that Mackup creates symlinks that cannot be stashed?

I didn’t want to re-install my plugins and themes, so I created a branch my-custom

All seems well. Hope this helps someone in future.

Sorry, but what am I supposed to do? =)

Isn’t the issue that Mackup creates symlinks that cannot be stashed?

I didn’t want to re-install my plugins and themes, so I created a branch my-custom

All seems well. Hope this helps someone in future.

This worked for me perfectly!

Sorry, but what am I supposed to do? =)

I’ld say — at least in the mean time until a working solution is found — remove oh-my-zsh from the mackup supported list since it breaks upgrading it?

Hi guys, I solved it like so:

/.zshrc , replace this:

@LucasLarson it sounds much better! Yeah. Thanks.

Hmm — this seemed to work and now it’s not.

/.zshrc , replace this:

Also tried the git checkout, git add, git merge workflow and got this:

Isn’t the issue that Mackup creates symlinks that cannot be stashed?

I didn’t want to re-install my plugins and themes, so I created a branch my-custom

All seems well. Hope this helps someone in future.

This is great, thanks for sharing.

One problem I found though is that you can’t easily upgrade the next time, since your local master will differ from origin, which will leave you with a mess. I solved it a slightly different way (going to use the OMZ git aliases, since we’re in the project ;)):

Instead of merging, I rebased my custom branch to master .

Now when new commits are made to master , all I need to do is:

Источник

Откуда это перебазирование?

Недавно я создал новую ветку локально, опубликовал ее на удаленном компьютере и получил обновление от коллеги. Хотя у меня есть изменения в моем репозитории, ни один из них не относится к файлам, которые были изменены. Поэтому я ожидал, что git pull будет работать, как подразумевается в сообщении от git status :

Однако при извлечении появляется сообщение об ошибке, указывающее на то, что выполняется перебазирование:

Я не знаю, откуда это могло взяться, так как я никогда сознательно не выполнял перебазирование. Также, как ни странно:

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

Откуда ребаз? Почему команды git pull и git rebase не согласны с тем, есть ли перебазирование? Как я могу навести порядок в этом беспорядке?

2 ответа

Как указал @ coyotte508, вы, вероятно, настроили git pull на выполнение перебазирования вместо слияния, установив Параметр pull.rebase в вашем Файл конфигурации Git (глобально или в текущем репо).

Почему команды git pull и git rebase не согласны с тем, есть ли перебазирование?

Они этого не делают. git pull просто отказался выполнить перебазирование, потому что у вас есть незафиксированные изменения в вашем рабочем каталоге. К моменту выхода git pull перебазирование не выполняется.

Как я могу навести порядок в этом беспорядке?

Вы можете зафиксировать или сохранить изменения перед выполнением git pull ( rebase.autostash , который вы упомянули, сделает последнее за вас автоматически). В качестве альтернативы вы можете установить pull.rebase на false и заставить git pull выполнить обычное слияние, но Я бы не рекомендовал это.

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

Посмотрим, есть ли в одном из них true . В этом случае вы можете:

Источник

Git has a number of good features designed to improve user experience with Github and reduce the chances of data loss. Earlier I have explained about Solution: Github ‘Please tell me who you are’ error. Today I am going to explain about the common message which you might get when executing pull command.

Recently I was trying to run git pull –rebase command but I got message like

$ git pull rebase

Cannot pull with rebase: You have unstaged changes.

Please commit or stash them.

Git stash command is kind of commit stored changes to temporary space and clean working copy. Then your working copy will be reverted to HEAD.It is a good place to store uncommitted changes.

When you stash the changes, your changes will be stored in temporary space and your working copy will be reverted to HEAD

git pull –rebase is a good practice to use in general.This is very specific problem when you pull data from server so let’s check it with example

You have changes that have not been committed and you are going to pull changes from the server, you will get above error.This error says commit your local changes before you pull or stash changes mean store local changes to another place for temporary and get back with pop.

You can do this to work around using following steps

1. stash your changes with: git stash
2. pull from master with rebase: git pull –rebase
3. Then execute simpler git stash pop. With this command, it deletes that stash for good, while apply does not.

Here I have used git stash pop but After changes have been stashed, there are a few options of to get changes back to local:

1. git stash pop: This command takes a stashed change and removes changes from the stash stack and apply it to your current working tree.

2. git stash applies : This command takes a stashed change and applies it to your current working tree. You need to delete stash stack using git stash drop .

3. git stash branch: This command creates a new branch from the same commit you were on when you stashed the changes and applies the stashed changes to the new branch.

Experiment with the stash before using it on some really important work 🙂

Issue

I have started collaborating with a few friends on a project & they use the heroku git repository.

I cloned the repository a few days ago and they have since made some changes so I am trying to get the latest updates

I ran the git pull --rebase command as stated here(Is this the right way to do it?): https://devcenter.heroku.com/articles/sharing#merging-code-changes

I get the following error:

$ git pull --rebase
Cannot pull with rebase: You have unstaged changes.
Please commit or stash them.

My guess is that I messed around with the code and now it wants me to either commit or discard(is that what does stash means?) the changes. Is this what is happening? If this is the case I would like to discard any changes I might have made and just get the updated code from the git repository.

Any idea of what I can do?

Solution

Do git status, this will show you what files have changed. Since you stated that you don’t want to keep the changes you can do git checkout -- <file name> or git reset --hard to get rid of the changes.

For the most part, git will tell you what to do about changes. For example, your error message said to git stash your changes. This would be if you wanted to keep them. After pulling, you would then do git stash pop and your changes would be reapplied.

git status also has how to get rid of changes depending on if the file is staged for commit or not.

Answered By – Schleis

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

If you want to keep your working changes while performing a rebase, you can use --autostash. From the documentation:

Before starting rebase, stash local modifications away (see git-stash[1]) if needed, and apply the stash when done.

For example:

git pull --rebase --autostash

First start with a
git status

See if you have any pending changes.
To discard them, run

note that you will lose your changes by running this

git reset --hard

Do git status, this will show you what files have changed. Since you stated that you don’t want to keep the changes you can do git checkout -- <file name> or git reset --hard to get rid of the changes.

For the most part, git will tell you what to do about changes. For example, your error message said to git stash your changes. This would be if you wanted to keep them. After pulling, you would then do git stash pop and your changes would be reapplied.

git status also has how to get rid of changes depending on if the file is staged for commit or not.

Pulling with rebase is a good practice in general.

However you cannot do that if your index is not clean, i.e. you have made changes that have not been committed.

You can do this to work around, assuming you want to keep your changes:

  1. stash your changes with: git stash
  2. pull from master with rebase
  3. reapply the changes you stashed in (1) with: git stash apply [email protected]{0} or the simpler git stash pop

Tags:

Git

Heroku

Pull

Related

I opened a terminal window and Oh My Zsh wanted to check for updates.
I entered Y for yes and then I got the error message:

Cannot pull with rebase: You have unstaged changes.
Please commit or stash them.

I tried git status and Git told me that the current directory wasn’t a repository (which didn’t surprise me).

So, what is it complaining about?

asked Jun 3, 2015 at 15:30

n8mob's user avatar

3

You made a changes to the config files probably.
Go to your oh-my-zsh directory and type in git status.

Results for me (i’ve changed one of the themes):

╭─ jane  ~
╰─ λ cd .oh-my-zsh                                                      1:57:10
╭─ jane  ~/.oh-my-zsh  ‹master*›
╰─ λ git status                                                         1:57:17
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   themes/bira.zsh-theme

no changes added to commit (use "git add" and/or "git commit -a")

You will see that some files have been modified.

You can type in git stash to temporarily get rid of those changes, and attempt updating again.

answered Jun 4, 2015 at 23:59

mnmnc's user avatar

mnmncmnmnc

3,9831 gold badge19 silver badges24 bronze badges

Here is what I had to do to fix it:

cd ~/.oh-my-zsh/
git add .
git commit -m "commit message"
upgrade_oh_my_zsh

Don’t forget the «.» at the end of 2nd line

answered May 18, 2017 at 13:16

Stryker's user avatar

StrykerStryker

1911 silver badge6 bronze badges

1

Oneliner solution

cd "$ZSH" && git stash && upgrade_oh_my_zsh && git stash pop
  1. cd "$ZSH" change tu current ZSH directory.
  2. git stash stage your local changes and head back to master via git.
  3. upgrade_oh_my_zsh upgrade ohMyZsh
  4. git stash pop to keep the changes, probably your themes.

answered Feb 20, 2020 at 13:16

Exequiel Barrirero's user avatar

If you’re okay with dropping any of your local changes, then run:

git checkout -f master
git pull

This makes sure you’re up to date and removes any mess from your local machine.

answered May 18, 2022 at 19:10

Janac Meena's user avatar

Janac MeenaJanac Meena

2032 silver badges10 bronze badges

Ошибка: не удается вытащить с ребазом: у вас есть не внесенные изменения


Я начал сотрудничать с несколькими друзьями по проекту, и они используют хранилище heroku git.

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

Я выполнил git pull --rebaseкоманду, как указано здесь (это правильный способ сделать это?): Https://devcenter.heroku.com/articles/sharing#merging-code-changes

Я получаю следующую ошибку:

$ git pull --rebase
Cannot pull with rebase: You have unstaged changes.
Please commit or stash them.

Я предполагаю, что я возился с кодом, и теперь он хочет, чтобы я либо зафиксировал, либо отклонил (это означает, что значит stash?) Изменения. Это то, что происходит? Если это так, я бы хотел отменить все внесенные мной изменения и просто получить обновленный код из репозитория git.

Есть идеи, что я могу сделать?

Ответы:


Сделайте git status, это покажет вам, какие файлы изменились. Поскольку вы заявили, что не хотите сохранять изменения, которые вы можете сделать, git checkout -- <file name>или git reset --hardизбавиться от них.

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

git status также есть, как избавиться от изменений в зависимости от того, находится ли файл для фиксации или нет.






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

Перед началом ребазирования, при необходимости, спрячьте локальные модификации (см. Git-stash [1] ) и примените тайник, когда закончите.

Например:

git pull --rebase --autostash







Тяга с ребазом — это хорошая практика в целом.

Однако вы не можете сделать это, если ваш индекс не чистый, то есть вы внесли изменения, которые не были зафиксированы.

Вы можете сделать это, чтобы обойти, если вы хотите сохранить свои изменения:

  1. сохранить ваши изменения с: git stash
  2. вытащить из мастера с ребаз
  3. повторно применить изменения, которые вы спрятали в (1) с: git stash apply stash@{0}или более простымgit stash pop






Сначала начните с
git status

Посмотрите, есть ли у вас ожидающие изменения. Чтобы отбросить их, беги

git reset --hard



Это работает для меня:

git fetch
git rebase --autostash FETCH_HEAD



Вы всегда можете сделать

git fetch && git merge --ff-only origin/master

и вы либо не получите (а) никаких изменений, если у вас есть незафиксированные изменения, которые конфликтуют с вышестоящими изменениями, либо (б) тот же эффект, что и у stash / pull / apply: ребаз, чтобы поставить вас на последние изменения из HEAD, и ваши незафиксированные изменения остались как есть.


Когда неустановленное изменение происходит из-за того, что git пытается исправить условные обозначения eol в файле (как всегда в моем случае), никакое сохранение или извлечение или сброс не заставит его исчезнуть.

Однако, если цель является действительно перебазироваться и игнорировать unstaged изменилось, то , что я делаю , это удалить ветвь локально затем проверить его снова.

git checkout -f anyotherbranchthanthisone
git branch -D thebranchineedtorebase
git checkout thebranchineedtorebase

Вуаля! Это еще не подвело меня.


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

git config --global rebase.autoStash true


«Fixed». Please pull master…

This scenario should be very familiar to you.

«You are coding an important feature.

Git status reveals a large number of uncommitted
changes.

As you test your feature, the app reports a nasty crash/bug/assertion on a
different module. As you are blocked from testing, you reach out to the owner.

The code owner informs you that he pushed a fix a few moments ago.»

If you have worked in a team environment, you should at least once experienced the scenario above.
I definitely have, especially working on a codebase with 1000 or more daily commits ( we use git as our version control ).

Well, what would you do? The most common step is to pull master to retrieve the fix.
So, you run back to your desk, and execute git pull --rebase.

I am a fan of git rebase. I think that using rebase makes git history so much cleaner and easier to maintain.

Instead of getting a list of file changes or commits, your terminal reports this error:

❯ git pull
error: cannot pull with rebase: You have unstaged changes.
error: please commit or stash them.

Enter fullscreen mode

Exit fullscreen mode

Translation: «You still have work in progress and I don’t want to mess up and overwrite
your changes. Please commit or temporarily shelve your work.»

Since you have uncommitted changes, you can’t pull from master.
You could commit your changes and move on.

Emphasizing the word: commit — I personally think every commit should
be workable, compilable and maintainable code
( else I would rename git commit to git save )

Back to our problem — there is an easier way.

How to pull changes while having uncommitted changes?

Use Git Stash command.

Git Stash excels in these types of scenarios
(where you need to pull the latest code changes while not being ready to commit your
own changes).

git stash is a git command that allows you to temporarily shelve
or put aside uncommitted changes.
You are then free to update your local copy.
And can immediately continue where you left off by popping your stash.

Back to our scenario, I would execute git stash with:

git stash -u

Enter fullscreen mode

Exit fullscreen mode

The -u sign is optional but I find it very handy. It tells git stash to include
new files ( git stash untracked files ).

Now you’re left with a clean working tree. Hopefully, git pull --rebase should be able
to work.
To continue where you left off, use git stash pop.

git stash pop

Enter fullscreen mode

Exit fullscreen mode

This will pop the latest stash to your working directory.
And that’s it, you have successfully pulled master without committing your local changes
with just 3 commands.

  1. git stash -u
  2. git pull —rebase
  3. git stash pop

Automation with «rebase.autostash»

I don’t know about you but writing 3 commands every time does get tiring.

So, can «git pull» auto stash and pop pending changes? Yes.

You could create a special git alias that runs all 3 commands in order.

However, since Git version 2.7,
a new global config flag ( rebase.autostash ) was introduced that automates stashing. Amazing!

By default, this flag is set to false. Enable it globally by running:

git config --global rebase.autostash true

Enter fullscreen mode

Exit fullscreen mode

Now, whenever you run git pull --rebase, your local changes will automatically be stashed
and popped back. Pretty neat.

Wrap up

Git stash shines in scenarios when you’re stuck between pulling master
and having a dirty working copy
( especially during moments when your boss comes in and demands that you fix something immediately ).

Paired with rebase.autoStash, my daily git experience is smooth and easy.

Finally, I highly recommend visiting git-stash documentation page,
if you want to know more about the different modes of git stash.

Понравилась статья? Поделить с друзьями:
  • Error cannot open trainz asset database
  • Error cannot open recovery img
  • Error cannot open file fsgame ltx check your working folder ок
  • Error cannot open file fsgame itx check your working folder
  • Error cannot open file for writing