Git ошибка при push

(Note: starting Oct. 2020, any new repository is created with the default branch main, not master. And you can rename existing repository default branch from master to main.
The rest of this 2014 answer has been updated to use «main«)

(The following assumes github.com itself is not down, as eri0o points out in the comments: see www.githubstatus.com to be sure)

If the GitHub repo has seen new commits pushed to it, while you were working locally, I would advise using:

git pull --rebase
git push

The full syntax is:

git pull --rebase origin main
git push origin main

With Git 2.6+ (Sept. 2015), after having done (once)

git config --global pull.rebase true
git config --global rebase.autoStash true

A simple git pull would be enough.
(Note: with Git 2.27 Q2 2020, a merge.autostash is also available for your regular pull, without rebase)

That way, you would replay (the --rebase part) your local commits on top of the newly updated origin/main (or origin/yourBranch: git pull origin yourBranch).

See a more complete example in the chapter 6 Pull with rebase of the Git Pocket Book.

I would recommend a:

# add and commit first
#
git push -u origin main

# Or git 2.37 Q2 2022+
git config --global push.autoSetupRemote true
git push

That would establish a tracking relationship between your local main branch and its upstream branch.
After that, any future push for that branch can be done with a simple:

git push

Again, with Git 2.37+ and its global option push.autoSetupRemote, a simple git push even for the first one would do the same (I.e: establishing a tracking relationship between your local main branch and its upstream branch origin/main).

See «Why do I need to explicitly push a new branch?».


Since the OP already reset and redone its commit on top of origin/main:

git reset --mixed origin/main
git add .
git commit -m "This is a new commit for what I originally planned to be amended"
git push origin main

There is no need to pull --rebase.

Note: git reset --mixed origin/main can also be written git reset origin/main, since the --mixed option is the default one when using git reset.

Время на прочтение
6 мин

Количество просмотров 65K

В финальной части нашей серии статей о работе с Git мы продолжим разговор о ветках, рассмотрим особенности работы с командой push и расскажем, что такое rebase. Первую и вторую статьи серии вы можете прочитать по ссылкам.

Глава 16. Откуда взялась ветка?

Набираемся терпения и продолжаем рассматривать разные рабочие ситуации. Если мы сделаем несколько коммитов, а потом выполним команду fetch (скачаем свежие коммиты, но пока не применим их в рабочий каталог), то увидим немного сбивающую с толку картину:

Что это ещё за ветка получилась? Мы ведь не создавали никакой ветки. Может её создал кто-то из сотрудников? Нет, никто её не создавал. Восстановим хронологию событий:

  • Сначала мы скачали свежие коммиты. Тогда последним был коммит «2».
  • Затем мы сделали коммиты «3» и «4» (но пока не пушили их).
  • В это время другие сотрудники запушили в удалённый репозиторий коммиты «5», «6» и «7». Тогда мы ничего не знали об этом.
  • Наконец, мы сделали fetch и увидели то, что на картинке.

В Git каждый коммит хранит ссылку на предыдущий (это и позволяет нам соединять кружки на рисунках; каждый отрезок – это ссылка на предыдущий коммит). Когда мы сделали коммит «3», для нас последним коммитом был «2» поэтому они соединены. Но когда на origin кто-то запушил коммит «5», там последним был тоже коммит «2» –  ведь мы свои коммиты «3» и «4» ещё не запушили, и на origin их не было. А раз так, то для коммита «5» предыдущим тоже выступает коммит «2», именно эту связь Git и запомнил.

Итого, разные люди независимо друг от друга поменяли результат коммита «2» – вот и возникла ветка. Кстати, эта ветка сейчас есть только в нашем локальном репозитории. В origin её пока нет, поскольку коммиты «3» и «4» мы до сих пор не запушили.

Что дальше? Поскольку мы сделали fetch, а не pull, то скачанные коммиты ещё не применились к нашему рабочему каталогу. Давайте применим их – для этого выполним merge. Результат представлен на картинке:

Произошедшее уже знакомо нам. Образовался автоматический merge-commit «8» – master и head теперь указывают на него. В рабочей копии появились изменения из коммитов «5», «6» и «7», которые объединились с нашими изменениями из коммитов «3» и «4». origin/master по-прежнему указывает на «7», поскольку последние наши операции проходили на локальном компьютере. А origin/master может сдвинуться только после общения нашего репозитория с origin.

Наконец, делаем push, и вот теперь origin/master тоже указывает на «8», ведь:

  • Наш merge-commit «8» отправлен в origin.
  • Там он стал последним, а значит удалённый указатель master теперь показывает на него.
  • Нам скачалась информация об удалённом указателе master и мы её видим как origin/master.

Вот он и показывает на «8». Логично.

Не поддавайтесь малодушному желанию пропустить эти объяснения. В них нет ничего сложного, нужна лишь внимательность. Обязательно пройдитесь по шагам до тех пор, пока не поймете, почему все так работает.

Глава 17. Почему push выдаёт ошибку?

Вы обязательно столкнетесь с тем, что Git выдаёт ошибку при команде push. В чём проблема? Почему он не принимает наши коммиты? Push успешно завершится, только если для каждого отправляемого в origin коммита Git сможет найти предшественника. Пример:

Здесь слева изображены коммиты в вашем локальном репозитории, а справа – коммиты в удалённом репозитории (origin).

Хронология этих коммитов следующая:

  • Сначала в origin были коммиты «1» и «2».
  • Мы сделали pull (в локальном репозитории тоже оказались лишь эти два коммита).
  • Потом мы закоммитили «3» и «4» в локальный репозиторий (но не пушили).
  • Кто-то запушил коммит «5» в origin.

И получилось то, что сейчас на картинке. Разобрались?

Теперь наша попытка запушить «3» и «4» в origin завершится ошибкой. Git откажется пристыковать наши коммиты к последнему коммиту «5» в origin, поскольку в local предшественником для коммита «3» является коммит «2» – а вовсе не «5», как в origin! Для Git важно, чтобы предшественник был тот же.

Проблема решается легко. Перед тем, как сделать push, мы сделаем pull (забираем коммит «5» себе). Тут вы можете спросить: «Секунду! А почему это забрать коммит «5» Git может, а послать коммиты «3» и «4» он не может? Вроде же ситуация симметричная в обе стороны». Правильный вопрос! А ответ на него простой. Если бы Git позволил отправить коммиты «3» и «4» в такой ситуации, то пришлось бы делать merge на стороне origin – а кто там будет разрешать конфликты? Некому. Поэтому Git заставляет вас сначала забрать свежие коммиты себе, сделать merge на своем компьютере (если будут конфликты, то разрешить их), а уже готовый результат он позволит вам отправить в origin командой push. При этом, никаких конфликтов в origin уже быть не может.

Давайте посмотрим, как будет выглядеть локальная история, после того, как вы заберете коммит «5» командой pull.

Здесь у «3» и «5» предок «2», как и на предыдущей картинке. А новый коммит «6» – это уже давно известный нам merge-commit.

В таком состоянии локальные коммиты уже можно запушить. Пусть тут и появилось разветвление истории, но обе ветки при мерже объединились. А значит голова у ветки снова одна. То есть, ничего не мешает сделать push. После этого в origin коммиты будут выглядеть такой же точно «петелькой».

Теперь, когда push выдаст вам ошибку, вы уже знаете почему и что с этим делать.

Глава 18. Rebase

В предыдущей главе мы сделали несколько локальных коммитов, а потом командой pull забрали коммиты других сотрудников из удалённого репозитория. У нас в локальном репозитории образовалась как бы «ветка», которая потом обратно объединилась с основной. После push это временное раздвоение ветки попало в origin, откуда его скачают сотрудники и увидят в своей истории. Часто такие «петли» считаются нежелательными. Поскольку вместо красивой линейной истории получается куча петель, которые затрудняют просмотр.

Git предлагает альтернативу. Выше мы делали fetch+merge. Первая команда забирает свежие коммиты, вторая объединяет их с нашими незапушенными коммитами (если они есть) и создаёт merge-commit с результатом объединения.

Так вот, оказывается можно вместо fetch+merge делать fetch+rebase. Что за rebase и чем он отличается от merge? Вспомним ещё раз, как проходил merge в предыдущем примере:

Rebase действует по-другому – он отсоединяет вашу цепочку незапушенных коммитов от своего предка. Напомним, это были коммиты «3» и «4». Они отсоединяются от своего предка «2» и rebase ставит их «сверху» на только что скачанный коммит «5». То есть, «3» и «4» будут прицеплены сверху к «5» (а мерж-коммит «6» вообще не появится). Итог будет таким:

Никакой петли больше нет, история линейная и красивая! Да здравствует rebase! Теперь мы знаем, что при скачивании коммитов из origin лучше объединять их со своими локальными коммитами при помощи rebase, а не merge.

Хорошо, а если речь не о паре-тройке ваших коммитов, а о большой ветке с разработкой новой фичи. Когда настанет время влить эту фичу в главную ветку, как это лучше сделать – через rebase или merge? У обоих способов есть преимущества:

  • rebase позволит сохранить историю простой и линейной – он добавит цепочку ваших коммитов из ветки в конец основной ветки.
  • merge сделает петлю, но зато в истории более наглядно будет прослеживаться история разработки вашей фичи.

Вопрос предпочтения rebase или merge в таких случаях обсудите с ведущим программистом вашего проекта.

Глава 19. Эпилог

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

  • pull
  • commit
  • push
  • add
  • clone
  • checkout
  • stash
  • merge
  • rebase
  • abort
  • fetch

Это не все команды, которые бывают нужны в работе – только самые частые. Будьте готовы, что потребуется освоить и другие. Работать с Git можно при помощи разных git-клиентов. Мы в основном используем эти три:

  • Консольный
  • SourceTree
  • TortoiseGit

Выбор клиента – дело вкуса.

Консольный – работает на всех платформах, но у него крайне аскетичный интерфейс. Если вы не привыкли работать в консоли, то скорее всего вам будет в нем некомфортно.

SourceTree — графический клиент с довольно простым интерфейсом. Есть версии для наших основных платформ: Win и Mac. Однако, сотрудники часто жалуются на его медленную работу и глюки.

TortoiseGit — еще один графический клиент. Есть версия для Win, для Mac`а нет. Интерфейс несколько непривычный, но многим нравится. Жалоб на глюки и тормоза существенно меньше, чем в случае с SourceTree.

Интересно, что и SourceTree, и TortoiseGit не работают с репозиторием Git напрямую. Внутри себя они используют консольный Git. Когда вы нажимаете на красивые кнопки, вызываются консольные команды Git с разными хитрыми параметрами, а результат вызова снова показывают в красивом виде. Использование всеми клиентами консольного Git означает, что все они работают со стандартной файловой структурой Git-хранилища на вашем жёстком диске. А значит можно использовать смешанный стиль работы: одни операции выполнять в одном клиенте, а другие – в другом.

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

Успехов!

Git: советы новичкам – часть 1
Git: советы новичкам – часть 2
Git: советы новичкам – часть 3

I ran these commands below:

git add .
git commit -m 't'

Then, when running the command below:

git push origin development

I got the error below:

To git@github.com:myrepo.git
 ! [rejected]        development -> development (non-fast-forward)
error: failed to push some refs to 'git@github.com:myrepo.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

Are there any ways to solve the error above?

Super Kai - Kazuya Ito's user avatar

asked May 25, 2012 at 11:00

Tampa's user avatar

Your origin repository is ahead of your local repository. You’ll need to pull down changes from the origin repository as follows before you can push. This can be executed between your commit and push.

git pull origin development

development refers to the branch you want to pull from.
If you want to pull from master branch then type this one.

git pull origin master

akshay_rahar's user avatar

akshay_rahar

1,6612 gold badges18 silver badges20 bronze badges

answered May 25, 2012 at 11:08

Dan Lister's user avatar

Dan ListerDan Lister

2,5631 gold badge21 silver badges36 bronze badges

1

In my case Github was down.

Maybe also check https://www.githubstatus.com/

You can subscribe to notifications per email and text to know when you can push your changes again.

answered Jul 22, 2019 at 15:54

Oscar Wieman's user avatar

I have faced the same issue and resolved as follows
(if you have a project in local folder then follow the steps):

  1. create a new repo in GitHub
  2. go to local folder and do «git init»
  3. git remote add origin (with your repo url) // simply copy from your repo
  4. git add -A
  5. git commit -m «your commit»
  6. git push -u origin master

Community's user avatar

answered Apr 2, 2019 at 9:44

Umair Arshad's user avatar

I also got the error ! [remote rejected] main -> main (failure) error: failed to push some refs to '<repository>'.

Came to find out this is the reason:

enter image description here

answered Aug 10, 2021 at 15:38

Fiddle Freak's user avatar

Fiddle FreakFiddle Freak

1,9655 gold badges43 silver badges83 bronze badges

In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:

git add .
git commit -m"commentary"

Then I was able to type:

git push -u origin master

answered Nov 25, 2019 at 17:32

iargdel's user avatar

iargdeliargdel

611 silver badge5 bronze badges

I used this command and it worked fine with me:

>git push -f origin master

But notice, that may delete some files you already have on the remote repo. That came in handy with me as the scenario was different; I was pushing my local project to the remote repo which was empty but the READ.ME

answered Aug 4, 2018 at 12:29

Amado Saladino's user avatar

you can write in your console:

git pull origin

then press TAB and write your «master» repository

answered Sep 3, 2012 at 18:02

Epredator's user avatar

EpredatorEpredator

1093 silver badges8 bronze badges

Try this:

  1. git push -u origin master
  2. git push -f origin master

Sometimes #1 works and sometimes #2 for me. I am not sure why it reacts in this way

answered Aug 20, 2020 at 19:17

Vrushil Soni's user avatar

2

In windows, you need to use double quotes «». So the command would be

git commit -m «t»

answered Apr 11, 2014 at 6:32

Tui Popenoe's user avatar

Tui PopenoeTui Popenoe

2,0982 gold badges23 silver badges44 bronze badges

In my case git push was trying to push more that just the current branch, therefore, I got this error since the other branches were not in sync.

To fix that you could use: git config --global push.default simple
That will make git to only push the current branch.

This will only work on more recent versions of git. i.e.: won’t work on 1.7.9.5

answered Jan 29, 2015 at 15:22

douglaslps's user avatar

douglaslpsdouglaslps

8,0782 gold badges35 silver badges55 bronze badges

This command worked for me:

git push --set-upstream origin master

And if it doesn’t work, please make sure that you are pushing on the current branch that you are on it.

App University>git branch
* master
  test

And after that, you must push your code on the master branch

 App University>git push origin master

answered Jun 20, 2021 at 17:57

Abbas Jafari's user avatar

Abbas JafariAbbas Jafari

1,5022 gold badges16 silver badges28 bronze badges

1

$ git fetch --unshallow origin
$ git push you remote name

CAFEBABE's user avatar

CAFEBABE

3,9831 gold badge19 silver badges38 bronze badges

answered Mar 14, 2016 at 15:06

sam.hu's user avatar

I have faced below error
$ git push origin main
error: src refspec main does not match any
error: failed to push some refs to ‘https://github.com/———/git-init-sample.git’

Solution : I was not connected to git local repo https://github.com/login/oauth/authorize?response_type=

Once i connected error gone

$ git push origin main
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.

answered Dec 15, 2021 at 23:20

Rajvp's user avatar

1

This same error but with a different details can be related to changes to privacy settings in the repository. The details are very clear actually.

In example: I changed my profile settings to hide my email address and that has an effect in all my repositories.
However you can keep that setting checked and uncheck «Block command line pushes that expose my email» option in the Email Setting section

answered Jan 30, 2022 at 19:16

Karmavil's user avatar

KarmavilKarmavil

86310 silver badges13 bronze badges

I could push with «—force»:

git push origin --force

answered Jun 7, 2022 at 15:18

Super Kai - Kazuya Ito's user avatar

Sometimes, Git can’t make your change to a remote repository without losing commits. When this happens, your push is refused.

If another person has pushed to the same branch as you, Git won’t be able to push your changes:

$ git push origin main
> To https://github.com/USERNAME/REPOSITORY.git
>  ! [rejected]        main -> main (non-fast-forward)
> error: failed to push some refs to 'https://github.com/USERNAME/REPOSITORY.git'
> To prevent you from losing history, non-fast-forward updates were rejected
> Merge the remote changes (e.g. 'git pull') before pushing again.  See the
> 'Note about fast-forwards' section of 'git push --help' for details.

You can fix this by fetching and merging the changes made on the remote branch with the changes that you have made locally:

$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

Or, you can simply use git pull to perform both commands at once:

$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work

Error: failed to push some refs to – How to Fix in Git

When collaborating with other developers using Git, you might encounter the error: failed to push some refs to [remote repo] error.

This error mainly occurs when you attempt to push your local changes to GitHub while the local repository (repo) has not yet been updated with any changes made in the remote repo.

So Git is trying to tell you to update the local repo with the current changes in the remote before pushing your own changes. This is necessary so that you don’t override the changes made by others.

We’ll be discussing two possible ways of fixing this error in the sections that follow.

We can fix the error: failed to push some refs to [remote repo] error in Git using the  git pull origin [branch] or git pull --rebase origin [branch] commands. In most cases, the latter fixes the error.

Let’s go over how you can use the commands above.

How to Fix error: failed to push some refs to Error in Git Using git pull

To send a pull request means to «fetch» new changes made to the remote repo and merge them with the local repo.

Once the merging is done, you can then push your own code changes to GitHub.

In our case, we’re trying to get rid of the error: failed to push some refs to [remote repo] error by sending a pull request.

Here’s how you can do that:

git pull origin main

If you’re working with a different branch, then you’d have to replace main in the example above with the name of your branch.

Just keep in mind that there are chances of failure when using this command to sync your remote and local repos to get rid of the error. If the request succeeds, then go on and run the command below to push your own changes:

git push -u origin main

If the error persists, you’ll get an error that says: fatal: refusing to merge unrelated histories. In that case, use the solution in the next section.

How to Fix error: failed to push some refs to Error in Git Using git pull --rebase

The git pull --rebase  command is helpful in situations where your local branch is a commit behind the remote branch.

To fix the error, go on and run following commands:

git pull --rebase origin main

git push -u origin main 

If the first command above runs successfully, you should get a response that says: Successfully rebased and updated refs/heads/main.

The second command pushes your local repo’s current state to the remote branch.

Summary

In this article, we talked about the error: failed to push some refs to [remote repo] error.

This error occurs when you attempt to push your local changes to the remote repo without updating your local repo with new changes made to the remote repo.

We discussed two commands that you can use to fix the error: the git pull origin [branch] and git pull --rebase origin [branch] commands.

I hope this helps you fix the error.

Happy coding!



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

Понравилась статья? Поделить с друзьями:
  • Gitlab 502 ошибка
  • Github ошибка авторизации
  • Github как сообщить об ошибке
  • Github push ошибка 403
  • Gilgen ошибка 2000