Fetch first git ошибка

The answer is there, git is telling you to fetch first.

Probably somebody else has pushed to master already, and your commit is behind. Therefore you have to fetch, merge the changeset, and then you’ll be able to push again.

If you don’t (or even worse, if you force it by using the --force option), you can mess up the commit history.

EDIT: I get into more detail about the last point, since a guy here just gave the Very Bad Advice of using the --force option.

As git is a DVCS, ideally many other developers are working on the same project as you, using the same repository (or a fork of it). If you overwrite forcefully with your changeset, your repository will mismatch other people’s, because «you rewrote history». You will make other people unhappy and the repository will suffer. Probably a kitten in the world will cry, too.

TL;DR

  1. If you want to solve, fetch first (and then merge).
  2. If you want to hack, use the --force option.

You asked for the former, though. Go for 1) always, even if you will always use git by yourself, because it is a good practice.

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

Данная статья не ставит перед собой цель быть энциклопедией решений на все случаи жизни. Было бы неверным давать ответы на вопросы, которые на данном этапе изучения Git просто не могут возникнуть. Любая информация должна соответствовать вашему текущему уровню.

1. Самое простое решение многих проблем

Вы «натворили делов» со своим репозиторием, и вам кажется, что все сломалось и ничего не работает. В качестве максимально быстрого решения этой проблемы можно удалить локальный репозиторий (скрытую папку .git в корне вашего проекта) и репозиторий на GitHub, а затем выполнить git init. При этом ваши файлы удалять не нужно.

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

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

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

2. Как изменить URL удаленного репозитория?

Вы неверно назвали свой репозиторий, например, вместо StartJava почему-то написали Lesson1 или JavaOps. На что наставник вам сказал, что его нужно переименовать.

Или вы удалили свой репозиторий на GitHub, а у себя на компьютере — оставили. После этого создали новый удаленный репозиторий (УР), изменив его первоначальное имя.

Например, URL репозитория выглядел так:


https://github.com/ichimax/lesson1.git

А после изменений ссылка стала следующей:


https://github.com/ichimax/startjava.git

При этом в настройках локального репозитория (ЛР) адрес старого репозитория никуда не делся — его нужно обновить.

Свяжем ЛР с новым адресом УР:


> git remote set-url origin новый_url.git
> git remote -v

Когда вам в дальнейшем потребуется выполнить push, то необходимо будет написать полную версию команды git push -u origin master, чтобы заново связать ЛР с новым УР, а затем снова можете использовать сокращенный вариант.

3. Как удалить файл из репозитория?

3.1. Удаление файла из индекса

Представим, что вы забыли занести в .gitignore правило, которое позволяло бы игнорировать class-файлы. В итоге применив команду git add, добавили их случайно в индекс.

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

Скомпилируем исходник, создав class-файл:

Внесем изменения в класс из предыдущих статей:


import java.util.Scanner;

public class MyFirstApp {
    public static void main(String[] args) {
        System.out.println("У какого языка программирования следующий слоган:");
        System.out.print(""Написано однажды, ");
        System.out.println("работает везде!"");

        String answer = new Scanner(System.in).next();
        if (answer.equalsIgnoreCase("Java")) {
            System.out.println("Вы угадали");
        } else System.out.println("Увы, но - это Java");
    }
}

Далее введем привычные команды:


> git add . && git status
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   MyFirstApp.class
        modified:   MyFirstApp.java

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

Воспользуемся командой, подсказанной Git:


> git restore --staged MyFirstApp.class && git status
Changes to be committed:
        modified:   MyFirstApp.java

Untracked files:
        MyFirstApp.class

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

Чтобы обезопасить себя, перед использованием команды git add, всегда нужно просматривать список файлов (git status), которые вы планируете добавить в индекс. Также обязательно добавьте шаблон *.class в .gitignore, чтобы больше не спотыкаться о class-файлы.

3.2. Удаление файла из коммита

Пойдем дальше и научимся удалять MyFirstApp.class из коммита.


> git status

Changes to be committed:
        new file:   MyFirstApp.class
        modified:   MyFirstApp.java

Добавим все изменения в коммит:


> git commit -m "Добавил quiz по слогану Java"

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


> git log -1 --name-only --oneline
ead5167 (HEAD -> master) Добавил quiz по слогану Java
src/MyFirstApp.class
src/MyFirstApp.java

С командной git log мы уже сталкивались в предыдущей статье. Из нового — аргумент —name-only, который позволяет вывести только имена измененных файлов, находящихся в коммите.

Использование log позволило заметить, что MyFirstApp.class оказался в коммите. Его нужно оттуда убрать.


> git reset --soft HEAD~1

Разберем эту команду по частям:

  • reset — отменяет коммиты
  • —soft — позволяет выполнить отмену коммита без потери изменений
  • HEAD — указатель на локальную ветку в которой мы находимся. В нашем случае HEAD~1 указывает на первый коммит в дереве коммитов ветки master

Более подробно про команду reset (1, 2).

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

Получается следующая картина: HEAD указывает на ветку master, а master является указателем на вершину в дереве коммитов.

Отобразим, куда указывает HEAD:

* обозначается текущая ветка.

Если команду ввести с параметром -v, то кроме названия ветки отобразится информация о коммите, на который указывает master:


> git branch -v
* master b59d871 Изменил вывод текста, отображаемого в консоль

После отмены коммита отобразим список оставшихся коммитов:


> git log --oneline
b59d871 (HEAD -> master, origin/master) Изменил вывод текста, отображаемого в консоль
39ba195 Переименовал about.txt в README.md и внес в него описание проекта
1e36e0f Инициализация проекта

Видим, что благодаря reset последний коммит из него был исключен.

При этом log отображает ту же самую информацию, о которой мы говорили выше: HEAD указывает на master, а он — на вершину дерева коммитов (коммит b59d871).

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

Посмотрим, в каком состоянии теперь находится ЛР:


> git status
Changes to be committed:
        new file:   MyFirstApp.class
        modified:   MyFirstApp.java

Что делать дальше, вы уже знаете: нужно убрать из индекса class-файл, и закоммитить java-класс.

Исключаем MyFirstApp.class:


> git restore --staged MyFirstApp.class
> git status
Changes to be committed:
        modified:   MyFirstApp.java

Untracked files:
        MyFirstApp.class

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

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


> git reflog
b59d871 (HEAD -> master, origin/master) HEAD@{0}: reset: moving to HEAD~1
ead5167 HEAD@{1}: commit: Добавил quiz по слогану Java

Из вывода видно описание отмененного коммита. Используем его для нового:


> git commit -m "Добавил quiz по слогану Java"

Больше подробностей о reflog по ссылке.

Не забудьте добавить *.class в.gitignore.

3.3. Удаление файла с GitHub

Самый неприятный случай — это когда мусорный файл все же пробрался на GitHub, т. е. был запушен:

В этом случае наставник вам может написать замечание: «на GitHub не должно быть файлов с расширением *.class, только *.java. Необходимо удалить из УР все class-файлы».

Самый простой выход из этой ситуации — это удалить в ЛР class-файлы, добавить в .gitignore маску *.class и сделать новый пуш. После этих действий на GitHub class-файл удалится. Он также автоматически удалится и у всех людей, которые работают с вами в одном репозитории. Например, когда наставник перед проверкой вашего ДЗ сделает git pull, то удаленные вами class-файлы, удалятся автоматически и у него.

Выглядеть это может примерно так:


D:JavaStartJava (master -> origin)
> git rm src*.class
rm 'src/MyFirstApp.class'


> git status
On branch master

Changes to be committed:
        new file:   .gitignore
        deleted:    src/MyFirstApp.class

> git commit -m "Добавил .gitignore с маской *.class"
[master 4bf0ddd] Добавил .gitignore с маской *.class
 2 files changed, 1 insertion(+)
 create mode 100644 .gitignore
 delete mode 100644 src/MyFirstApp.class

> git push

4. Как изменить описание коммита?

4.1. Коммит не был запушен

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

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


import java.util.Scanner;

public class MyFirstApp {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in, "cp866");
        System.out.print("Введите, пожалуйста, свое имя: ");
        String name = console.next();

        System.out.println("У какого языка программирования следующий слоган:");
        System.out.print(""Написано однажды, ");
        System.out.println("работает везде!"");

        String answer = console.next();
        if (answer.equalsIgnoreCase("Java")) {
            System.out.println(name + ", вы угадали!");
        } else System.out.println("Увы, но - это Java");
    }
}

> git add MyFirstApp.java
> git commit -m "Добавил ввод имени учасника"

Выясняется, что описание содержит опечатку в слове «учасника».

Для исправления воспользуемся двумя вариантами команды commit:

  • в первом случае при вводе git commit —amend, откроется редактор для изменения сообщения:

Такой способ подходит для исправления многострочных комментариев. Нам же больше подходит второй способ.

  • во втором случае команда ниже позволит внести изменение прямо из консоли:

> git commit --amend -m "Добавил ввод имени участника"
[master 96e2847] Добавил ввод имени участника

Убедимся, что описание к коммиту изменилось, а прежнее — не сохранилось, отобразив сокращенную информацию по последнему коммиту:


> git log --oneline -1
96e2847 (HEAD -> master) Добавил ввод имени участника

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

4.2.1. Принудительная перезапись истории

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

Чтобы решить эту задачу, необходимо к команде из предыдущего пункта добавить git push -f, которая принудительно перезапишет коммит с ошибочным описанием — исправленным:


> git commit --amend -m "Добавил ввод имени участника"
> git push -f

Среди прочего, в консоли отобразится примерно следующая строка:


+ 5aa3d6d...ce3cf6f master -> master (forced update).

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

У ваших коллег (или наставника) после ввода git pull отобразятся строки, тоже сообщающие о принудительном изменении и последующем успешном слиянии (merge):


+ 5aa3d6d...ce3cf6f master     -> origin/master  (forced update)
Merge made by the 'ort' strategy.

5. Как выполнить пуш, если Git не дает это сделать?

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

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


hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes

Возможна и другая ситуация, когда вы пушите в один репозиторий на GitHub с разных компьютеров. Например, днем, в свободное от работы время, порешали домашку, а затем запушили ее на удаленный репозиторий. Вечером, придя домой, продолжили писать код для следующего ДЗ. А про код, запушенный на GitHub, либо забыли, либо подумали, что из-за него проблем не будет. Но в действительности оказалось все иначе.

Или на GitHub случайно попали class-файлы и вы без задней мысли пошли на сайт и удалили их.

Во всех этих ситуациях пуш приведет к одной и той же ошибке, связанной с тем, что истории изменений на локальном и удаленном репозитории пошли разными путями: на GitHub есть коммит, которого нет в ЛР. В дереве коммитов на ЛР на какое-то количество коммитов меньше, чем на УР.

Научимся решать эту проблему.

5.1. Подтягивание изменений с GitHub

Зайдя в свой репозиторий на GitHub, я внес в README.md следующие мелкие изменения:

  • добавил картинку в виде шапки
  • пункт «Командная строка» заменил на конкретное название используемой программы — cmder
  • добавил иконки к каждому пункту списка

В качестве описания к коммиту указал следующий текст:

При этом README.md содержит следующий код:


# [StartJava](https://topjava.ru/startjava) -- курс на Java для начинающих

![image](https://user-images.githubusercontent.com/29703461/194078652-25a6e509-cdc6-4af4-9ab0-78b6b336c749.png)

## Используемые на курсе инструменты и технологии

:coffee: Java

:octocat: Git/GitHub

:pager: cmder

:bookmark_tabs: Sublime Text

:fire: Intellij IDEA

:gem: SQL

:elephant: PostgreSQL

:newspaper: psql

Проделанные только что изменения я благополучно забыл подтянуть на свой компьютер с помощью git pull. И продолжил работать над классом MyFirstApp.java в ЛР, добавив в него еще один квиз и немного мелких правок.

В итоге класс (у меня на компьютере, не в GitHub) стал выглядеть так:


import java.util.Scanner;

public class MyFirstApp {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in, "cp866");
        System.out.print("Введите, пожалуйста, свое имя: ");
        String name = console.nextLine();

        System.out.println("n1. У какого языка программирования следующий слоган:");
        System.out.print(""Написано однажды, ");
        System.out.println("работает везде!"");

        String answer = console.nextLine();
        if (answer.equalsIgnoreCase("Java")) {
            System.out.println(name + ", вы угадали!");
        } else System.out.println("Увы, но - это Java");

        System.out.println("n2. Какая фамилия у автора языка Java?");

        answer = console.nextLine();
        if (answer.equals("Гослинг") || answer.equals("Gosling")) {
            System.out.println(name + ", вы угадали!");
        } else System.out.println("Увы, но - это Гослинг (Gosling)");
    }
}

Добавил изменения в коммит:


> git add MyFirstApp.java
> git commit -m "Добавил quiz по автору Java"

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


> git log --oneline -1
7106587 (HEAD -> master) Добавил quiz по автору Java

А теперь самое интересное: попробуем сделать push:


> git push
To https://github.com/ichimax/startjava2.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/ichimax/startjava2.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

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

Для решения этой проблемы Git предлагает выполнить команду pull, которая подтянет коммиты с УР, а затем объединит их с локальными, чтобы выровнять историю:


> git pull
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), 1.16 KiB | 62.00 KiB/s, done.
From https://github.com/ichimax/startjava2
   ce3cf6f..2bdecf7  master     -> origin/master
Merge made by the 'ort' strategy.
 README.md | 25 +++++++++++++++++--------
 1 file changed, 17 insertions(+), 8 deletions(-)

В этом сообщении стоить обратить внимание на строку Merge made by the ‘ort’ strategy. Из нее мы можем сделать вывод, что произошло слияние (merge).

Слияние — это объединение истории коммитов из разных веток в одну. У нас ветка хоть и одна (master), но история коммитов на GitHub и в ЛР стала с какого-то момента различаться. Из-за этого и не удавалось сделать push. Когда мы выполнили git pull, то Git автоматически объединил (что бывает не всегда) последний коммит из УР с последним коммитом из ЛР, создав новый.

Не всегда Git может выполнить слияние автоматически, что вызывает конфликт слияния. Такое бывает, когда в разных ветках был изменен один и тот же фрагмент кода. Из-за этого Git не сможет определить, какую версию использовать. Для решения проблемы потребуется вмешательство пользователя. Более подробно об этом можно узнать по ссылке.

Для того, чтобы минимизировать возникновение подобных ситуаций (конфликтов), рекомендуется каждый раз перед началом работы с проектом делать git pull, чтобы синхронизировать историю коммитов ЛР с историей УР.

Отобразим 4 последних коммита:


> git log --oneline -4
1b4a7b7 (HEAD -> master) Merge branch 'master' of https://github.com/ichimax/startjava2
7106587 Добавил quiz по автору Java
2bdecf7 (origin/master) Обновил README.md
ce3cf6f Добавил ввод имени участника

Из этого списка видно, что:
2bdecf7 — был сделан на GitHub
7106587 — был сделан в ЛР
1b4a7b7 — получился автоматически после слияния двух предыдущих коммитов

Обратите внимание, что у коммита, сделанного на GitHub, ветка называется не master, а origin/master. Разница в том, что master — это имя локальной ветки, а origin/master является удаленной веткой с именем master.

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


> git branch -a
* master
  remotes/origin/master

Ветка master является текущей (помечена *) веткой ЛР. remotes/origin/master — это ветвь с именем master и псевдонимом origin на УР.

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


D:JavaStartJavasrc (master -> origin)
> git log --pretty=format:"%h - %s" --graph
*   1b4a7b7 - Merge branch 'master' of https://github.com/ichimax/startjava2
| 
| * 2bdecf7 - Обновил README.md
* | 7106587 - Добавил quiz по автору Java
|/
* ce3cf6f - Добавил ввод имени участника
* 4bf0ddd - Добавил .gitignore с маской *.class
* 90ca67c - Добавил quiz по слогану Java
* b59d871 - Изменил вывод текста, отображаемого в консоль
* 39ba195 - Переименовал about.txt в README.md и внес в него описание проекта
* 1e36e0f - Инициализация проекта

Опция —graph позволяет вывести граф в формате ASCII, который показывает текущую ветку и историю слияний. Более подробно с разными опциями команды log можно ознакомиться по ссылке.

Давайте взглянем на различия в последних коммитах в удаленной и локальной master-ветках:


D:JavaStartJavasrc (master -> origin)
> git diff origin/master..master
diff --git a/src/MyFirstApp.java b/src/MyFirstApp.java
index 8e25560..08099ad 100644
--- a/src/MyFirstApp.java
+++ b/src/MyFirstApp.java
@@ -4,15 +4,22 @@ public class MyFirstApp {
     public static void main(String[] args) {
         Scanner console = new Scanner(System.in, "cp866");
         System.out.print("Введите, пожалуйста, свое имя: ");
-        String name = console.next();
+        String name = console.nextLine();

-        System.out.println("У какого языка программирования следующий слоган:");
+       System.out.println("n1. У какого языка программирования следующий слоган:");
         System.out.print(""Написано однажды, ");
         System.out.println("работает везде!"");

-        String answer = console.next();
+        String answer = console.nextLine();
         if (answer.equalsIgnoreCase("Java")) {
             System.out.println(name + ", вы угадали!");
         } else System.out.println("Увы, но - это Java");
+
+        System.out.println("n2. Какая фамилия у автора языка Java?");
+
+        answer = console.nextLine();
+        if (answer.equals("Гослинг") || answer.equals("Gosling")) {
+            System.out.println(name + ", вы угадали!");
+        } else System.out.println("Увы, но - это Гослинг (Gosling)");
     }
 }

После всех манипуляций отобразим состояние репозитория:


> git status
On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)
 
nothing to commit, working tree clean

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


> git log --branches --not --remotes --oneline
1b4a7b7 (HEAD -> master) Merge branch 'master' of https://github.com/ichimax/startjava2
7106587 Добавил quiz по автору Java

Выполним push и снова введем команду, отображающую список из 4 коммитов:


> git push
> git log --oneline -4
1b4a7b7 (HEAD -> master, origin/master) Merge branch 'master' of https://github.com/ichimax/startjava2
7106587 Добавил quiz по автору Java
2bdecf7 Обновил README.md
ce3cf6f Добавил ввод имени участника

Видим, что история коммитов выровнялась: HEAD в ЛР и УР указывают на самый последний коммит 1b4a7b7.

Список решений тех или иных задач с помощью Git, разобранных в статье, с кратким описанием.

В статье мы рассмотрели самые простые, но часто возникающие проблемы, которые могут появиться при работе с Git и GitHub. Это базовый минимум, который поможет вам на первых порах не чувствовать себя растерянным, столкнувшись лицом к лицу с описанными сложностями.

Оцените статью, если она вам понравилась!

! [rejected] master -> master (fetch first) is an error message that occurs when Git rejects changes to a remote repository from your local repository because the remote repository was updated since you last fetched from it.Rejected Master Master Fetch First

This article will teach you everything about this error and how you can fix it in your Git repositories.

What you’ll learn about this error will let you understand how Git works and how a “last resort” can work for you when you’re out of options. Now, launch your terminal or command prompt, and let’s push your changes to your remote repository.

Contents

  • Why Did Git Reject Your Changes to the Remote Repository?
    • – Your Local Repository Is Outdated
  • How Git Can Accept Your Changes to a Remote Repository
    • – Fetch and Merge the Changes
    • – Pull the Latest Changes Using the “Git Pull” Command
    • – Reset Your Local Repository
    • – Stash Your Local Changes Using “Git Stash”
    • – Manually Resolve a Conflict
    • – Update Your Local Branch
    • – Force Your Changes to the Remote Repository
  • Conclusion
  • References

Why Did Git Reject Your Changes to the Remote Repository?

Git rejected your changes to the remote repository because your local repository is outdated and contains commits that are not present in the remote repository. Git did this to enable consistency in the remote repository and to stop you from overriding the work of another user.

– Your Local Repository Is Outdated

When your local repository is outdated, Git will not allow you to push any changes to an updated remote repository. That’s because if Git allows you to push to an updated repository, you can create a conflict that you’ll need to resolve.Your Local Repository Is Outdated

So, to prevent this, Git will check if your changes are compatible with the current state of the remote repository. If they’re not, Git will throw an error because it wants the repository to remain consistent and prevent conflicts between different versions of the same file.

How Git Can Accept Your Changes to a Remote Repository

Git can accept your changes to a remote repository if you fetch and merge the changes. You can also reset or stash your local repository.

Finally, you can update your local branch, manually resolve a conflict, and as a last resort, you can force your changes to the remote repository.



– Fetch and Merge the Changes

To solve the “! [rejected] master -> master (fetch first)” in Git, you can fetch and merge the changes from the remote repository into your local repository.

By doing this, you can update your local repository with the changes from the remote repository before trying “git push”. Now, use the following steps to fetch changes from a remote repository:

  1. Open your terminal or command prompt.
  2. Switch to the folder of the local repository that will receive the changes.
  3. Type “git fetch name_of_repo” to fetch the latest changes/commits from the remote repository and store them in your local repository.
  4. See the changes that “git fetch” downloads, using the “git log” command with the “–online and “–decorate” options. For example, “git log –online –decorate”.
  5. Merge the fetched changes into your local branch using the “git merge” command. For example, you can merge changes from “origin master” into your local repository using “git merge origin/master”.

Once you complete these steps, you can make changes in your local repository and send them to the remote repository using “git push”. With this, Git will not reject your changes, and everything should work.

– Pull the Latest Changes Using the “Git Pull” Command

The “git pull” command will fetch and merge changes from a remote repository in your local repository. This means it does the job of “git fetch” and “git merge” at the same time. To use “git pull” on your local repository, do the following:Rejected Master Master Fetch First Fixes

  1. Open your command prompt or terminal.
  2. Switch to the folder of the local repository on your computer.
  3. Type “git pull repo_name branch_name” where “repo_name” is the name of the repository and “branch_name” is the name of the branch that you want to fetch changes from.

Behind the scenes, when you run the “git pull” command, Git will retrieve the latest changes from “repo_name” and merge them into your local repository.

However, if you want the changes alone without Git merging them for you, use “git pull repo_name branch_name –rebase”. This will apply the changes to your local commits without merging them, and if there are conflicts, you’ll need to resolve them (we’ll teach you later in the article).

– Reset Your Local Repository

You can use “git reset” to reset your local repository to a state of the remote repository, and Git will allow your future “git push” commands.

Mind you, resetting your local repository will permanently destroy your local commits, and your local repository will synchronize with the remote repository. The following options are available with “git reset”, so select the best one that suits your use case:

  • “git reset –mixed <commit_id>” : Use this to move the branch pointer to a specific commit, and it will leave your changes in the commits as “unstaged”. This allows you to review your changes, and you can discard or keep them.
  • “git reset –soft <commit_id>” : Leave your changes in the commits as “staged” changes and move the branch pointer to a specific commit. With this, you can amend the commit message or add more to it before creating a new commit.
  • “git reset –hard <commit_id>” : This is a “delete all my local commits and changes” command. It will move the branch pointer to the specified commit and permanently delete all commits and changes made after the commit. So, use it with caution.

From above, the “<commit_id>” is a unique identifier for a commit, and it’s a string of characters that are generated based on the contents of the commit.  To get the latest “commit id” and commit message before you notice the “! [rejected] master -> master (fetch first)” error, use “git log -1 –format=%H%n%s”.

– Stash Your Local Changes Using “Git Stash”

If you want to keep your local changes on a repository and synchronize with the remote repository, use the “git stash” command. To use “git stash”, do the following:

  1. Open your terminal or command prompt.
  2. Switch to your local repository using the “cd” command.
  3. Type “git stash” to store your local changes. Behind the scenes, this command will move the changes from your current working directory to your stash.
  4. Perform other Git operations like fetching the latest commit from the remote repository.
  5. Use “git stash apply” to reapply your previous stash. This will bring your previous changes back into your current working directory.
  6. Use “git stash drop” if you don’t need your previous stashed changes.

– Manually Resolve a Conflict

Manual resolution of a conflict is the solution to the “rejected master” error if you made a change on a specific line of a file and another user also changed that same line before a merge. The following steps show you how to make a manual resolution of a conflict:

  1. Use the “git fetch” command to download the latest version of the repository.
  2. Use “git merge” to merge the conflicting branches where two users changed the same line of a file. If there are any overlapping changes, this will raise a conflict.
  3. Open the file that contains the conflict in your code editor and look for a section that begins with “<<<<<<<. This is where the conflict occurred.
  4. Select the changes that you want to keep, and delete the “<<<<<<<“, “=======”, and “>>>>>>>” along with changes that you don’t want to keep.
  5. Save the file and use “git commit” to commit your changes.
  6. Use “git push” to push your changes to the remote repository.

– Update Your Local Branch

Updating your local branch will synchronize it with the remote branch, and Git will accept your future “git push” command. To update your local branch, do the following:Rejected Master Master Fetch First Solutions

  1. Open your terminal or command prompt.
  2. Navigate to the local repository that contains the branch that you want to update.
  3. Use “git checkout” on the branch that you want to update. For example, “git checkout the_branch_name”.
  4. Download the latest changes from the remote repository using “git fetch”.
  5. Use the “git merge” command to merge the changes to your local branch. For example, “git merge origin/the_branch_name”.
  6. Resolve any conflict that arises.
  7. Use “git commit” to commit your changes. For example, “git commit -a”.
  8. Use the “git push” command to push your updated branch to the remote repository. For example, “git push origin the_branch_name”.

– Force Your Changes to the Remote Repository

Forcing your changes to the remote repository is the “last resort” that we mentioned in the introduction. It’s dangerous and irreversible and annoys the team members working on the same repository.

Now, to force your changes, open your terminal and run the “git push -f” command. But know that it will overwrite your teammate’s work on the repository.

Conclusion

This article explained why Git rejected your changes to a remote repository and solutions that you can use. We talked a lot about Git, and you should remember the following:

  • Git will reject changes to a remote repository if your local copy of the repository is outdated.
  • To solve the rejection error from Git, you can fetch and merge the latest changes from the Git repository.
  • The “git push -f” is the last resort that you can use if Git does not allow your local changes on the remote repository.

You can work with Git without getting the rejection error at this stage. Bookmark our article and read it the next time that Git rejects your “git push” changes.

References

  • https://learn.microsoft.com/en-us/azure/devops/repos/git/pulling?view=azure-devops&tabs=visual-studio-2022
  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

@JonnyD

I followed the instructions correctly but then when I go to push I get this error. The repo was up to date beforehand.

! [rejected] master -> master (fetch first)
error: failed to push some refs to »
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., ‘git pull …’) before pushing again.
hint: See the ‘Note about fast-forwards’ in ‘git push —help’ for details.

elvenbyte, ankit64jangir, tanaya2903-bornare, mdzakirhossain, nimamot, joshuaoweipadei, aslamanver, kyitharoo, Billo93, EdeVeerabhadra, and 62 more reacted with thumbs up emoji
MohammedTurk, msatti, and celse reacted with thumbs down emoji
TheGenocides, olinemoz, and bdseerden reacted with laugh emoji
mkrtich-mkrtchyan reacted with confused emoji

@rtyley

Are you sure you followed the instructions exactly?

http://rtyley.github.io/bfg-repo-cleaner/#usage

The error message you’re seeing is what you would see if you hadn’t used the ‘—mirror’ flag when doing the clone. To ensure you get a fully updated repo, it’s best to redo your clone, this time ensuring you use ‘—mirror’, and run The BFG again.

maibono, MarceLlanos, KaungSettHein, alexisartus96, sarfaraz-projects, RedhwanGhailan, amradelata, dp1170, gnanasekaran08, sangee2009, and 35 more reacted with thumbs up emoji
huykon, Aashu1081, Kiyocarl, DastySlasty, ShahidMehmoodAI, srezasm, THEJONHDOE, AhmedrAshraf, joshlul, knakamura13, and 31 more reacted with thumbs down emoji
anmol1432, azeem6755, harsh-vish14, ritu121, sanjitprd777, Giuliannabortone, SchoolWorkPrac, and Eman-Abu-Foul reacted with laugh emoji
yasertalha, lukasd181, sanjitprd777, nassimmnsr, and Eman-Abu-Foul reacted with hooray emoji
amar633, stevekama, vuminhloc, ToppYankah, Mustafa-Coder, Shubhanshu156, tariq7t, sarvagya2545, pritishaw1, sanjitprd777, and 6 more reacted with confused emoji
Ryzox-dev, developeratul, sanjitprd777, SnoozingSimian, heeyeonhan1734, Shreyass22, RinNguyens, Eman-Abu-Foul, and websoulashfaq reacted with rocket emoji
ToppYankah, VenkateshBoyapati, MayuranSundar, shruti960960, avd21, MuszynHub, sarvagya2545, Avisrivastwa, sanjitprd777, yuvrajdahal, and 4 more reacted with eyes emoji

@JonnyD

Thank you! I forgot to clone. It’s working now.

@javparra

Try this git command

git push origin master —force
or short of force -f

git push origin master -f

eduardaki, ileshgajjar, Noodle96, fdrandolfi, qingfeng825, muyik, javabrett, 0xAl3xH, Mehrshid, Bodrosh, and 1782 more reacted with thumbs up emoji
GreenGitHuber, belrvn, DangVanHao, Hetal06, mjasimuddin, Patle123, saurabhkumar8112, y97130663, mahmut094, UtmostCreator, and 152 more reacted with thumbs down emoji
achyuth1062, dangngoctuan, aminrasouli, kumochan, sittisuk, vami19, jahirgarzon, michaelDnguyen, anandtiwari767, kurt1993, and 193 more reacted with laugh emoji
aslamanver, aminrasouli, Nuta88, sittisuk, vami19, jahirgarzon, karthikutti, RedhwanGhailan, kurt1993, Dip-Ghosh, and 205 more reacted with hooray emoji
GreenGitHuber, dipu-m18, maibono, kuldeepoza, thisisajith, Arpanbhalla, pheshmati, javidnm, pranita-sawant, Kevin-Lev, and 62 more reacted with confused emoji
PriyankaSundar7, magdi-mohammed, sumyathlaing, taleymirza, smiftakhairul, UtkarshVerma, rajeshdumpeti, bmddp, bestopensource, dangngoctuan, and 366 more reacted with heart emoji
christianaifeanyichuku, lanceliamll, VitaliyBor, PaoCaro, mfreano24, movingStars, behnood-eghbali, tdrdimov, KaizhiDu, rachmandev, and 106 more reacted with rocket emoji
PaoCaro, mfreano24, movingStars, KaizhiDu, Shhzdmrz, T3NED, suchetaswabhav, 20161900240, vapaternina, ZeeshanAhmadKhalil, and 50 more reacted with eyes emoji

@heriipurnama

javparra, stap20, sebastien15, karaca, fouaddev, jpnaveenkumar, CikuKariuki, vishaljangir, behnood-eghbali, mohammad597, and 26 more reacted with thumbs up emoji
kingwebdev, lod616, behnood-eghbali, mridulk, medjamiaanes, suchetaswabhav, DavidKHahn, mohabmm, snehaagarwal625, TannyS26, and 7 more reacted with hooray emoji
xuancanyang, Tewetewe, behnood-eghbali, mssui, suchetaswabhav, DavidKHahn, LeF2019, venky1575, Amarnathojha071, MaramAlthobity, and 3 more reacted with heart emoji

@08shubhamjindal

javparra, karaca, thefakewater, fouaddev, jpnaveenkumar, Bhupi2508, cokeIII, arushgupta2007, DavidKHahn, mohabmm, and 9 more reacted with thumbs up emoji
kingwebdev, tokakamel2, codedeman, Priyanshu21101997, and NavidMansuri5155 reacted with thumbs down emoji
jayantkp reacted with confused emoji
fahadali32, edison-jace, Dat0318, and shyam-brainstream reacted with heart emoji
NavidMansuri5155 and datlt198640 reacted with eyes emoji

@qingfeng825

its working thanks @javprra

@gaurang444

it’s working nicely thanks for help @javparra

javparra, karaca, nitinbajpai110, arushgupta2007, DavidKHahn, and MuszynHub reacted with thumbs up emoji
kingwebdev, jpnaveenkumar, DavidKHahn, Daniils-stack, nivedha1599, and luth3rmilla reacted with heart emoji

@harsimarsingh8

@suyashgulati

@selfxss

@PriyankaSundar7

hey its working !!! thank you bro !!!

@sumyathlaing

@rajeshdumpeti

@saikumarbikki

@bestopensource

@aslamanver

@manisha-sinha01

@javparra

@Anirudh0509

@heltondenis

@kumochan

@namigaliyev


1 similar comment

@tuananhbui89

@chisom5

@mtalha91

I am having the same issue, use git remote -v to check the origin list
try changing git remote repo name by using git remote add origin [repo-url] and then push

@austinginder

Had same issue with a Beanstalk repo. Discovered by default they disable «non Fast-Forward pushes» on their end. To enable you need to check a box located https://[account-name].beanstalkapp.com/repositories/[git-repo]/edit.

@hostmakersyl

@f97-2308

@Velimir10

i found this helpfull, thanks!

@daniel-iroka

@EstopaceMA

@sagarguhe

In my case the local had different branch name and remote had different, so while I was on my local master branch was trying to push to remote main branch. Because I didn’t have any local main branch I renamed local master branch to main and then pushed, it worked!

@lovefromCode

git push origin master —force

Thank you very much @javparra

@CourtneyBritney

Try this git command

git push origin master —force
or short of force -f

git push origin master -f

Wow this worked. Thank you so much hey

@sattamalhamidy

sattams-MacBook-Pro:proj-sattam sattam$ git push origin main
To https://github.com/sattamalhamidy/proj-sattam.git
! [rejected] main -> main (fetch first)
error: failed to push some refs to ‘https://github.com/sattamalhamidy/proj-sattam.git’
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., ‘git pull …’) before pushing again.
hint: See the ‘Note about fast-forwards’ in ‘git push —help’ for details.

And I tried with git push origin main —force
But there is still the same bug

I have ssh key and also credential has no issue.
Hope someone saves my day.

@nethra400

@shwetaIAF

I followed the instructions correctly but then when I go to push I get this error. The repo was up to date beforehand.

! [rejected] master -> master (fetch first)
error: failed to push some refs to »
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., ‘git pull …’) before pushing again.
hint: See the ‘Note about fast-forwards’ in ‘git push —help’ for details.

I wanted to update my repo and first git pull then add and pushing worked for me thankyou so much.

@umairashraf2

Try this git ### command

git push origin master —force
or short of force -f

git push origin master -f

@GhanmiH

it doesn’t work with me :(

@Sarvinadewi22

@GhanmiH

@Volen99

Does not work here too :((

@lokeshloki1037

git push -u origin master
error: failed to push some refs to ‘github.com:lokeshloki1037/task.git’
git push origin master —force
error: src refspec master does not match any
error: failed to push some refs to ‘github.com:lokeshloki1037/task.git’
git push origin master -f
error: src refspec master does not match any
error: failed to push some refs to ‘github.com:lokeshloki1037/task.git’

still i am getting like this

@ShivaVkm

Try this git command

git push origin master —force
or short of force -f

git push origin master -f

thank you it worked

@gowrishankar10

Try this git command

git push origin master —force
or short of force -f

git push origin master -f

It worked. Thanks. @javparra

Yes it’s worked thank you @javparra

@Amosi-04-sanga

Try this git command

git push origin master —force
or short of force -f

git push origin master -f

Thanks, Now It’s Working.

@Vairaml

-force over wright the files in the repo, is there any other way

@pk-officl

In my case the local had different branch name and remote had different, so while I was on my local master branch was trying to push to remote main branch. Because I didn’t have any local main branch I renamed local master branch to main and then pushed, it worked!

How to do it?

@loverforcode

@ekBlaise

@AratiKashelkar12

@vijayparik

@kriticashk

@beydemirfurkan

its working thanks @javprra

@noamandev

oh my god thanks! it works now! Looks like a learned something new today @javparra

@NileshDeshmukh09

git push origin master -f

Thanks bro , it works for me , too!

@KaoutharBabi

Try this git command

git push origin master —force or short of force -f

git push origin master -f
it doesn’t work for me and i don’t know why could u help me please

@wakoliVotes

Hello, anyone got a better solution to:

! [remote rejected] main -> main (permission denied)

Tried the ‘git push origin master —force’, however, it is not working on my end.
My branch is ‘main’, so I used main

@YuvrajYashVerma

it worked for me ! thanks…..

What is ‘failed to push some refs to’ error

failed to push some refs to is a Git error that many developers frequently face. It occurs when a developer attempts to push committed code to an external git repository. The ability to push code stopped working suddenly, despite it working yesterday or the day before. It can be a source of frustration and annoyance for many.

failed to push some refs to errors are often caused when changes are not committed before pushing, issues with Git pre-push hook, incorrect branch name, or the local repository not being in sync with the Git repository. It occurs most of the time because multiple contributors are working on the same branch and the remote repository is further along than what you currently have on your local machine.

It is easy for git pushes to overlap when working in teams or for ref heads to be in different positions. This overlap can cause the repository to be out of sync, which is why the failed to push some refs to error are so frequent.

What causes ‘failed to push some refs to’ error

When multiple developers work on the same branch, it can cause a sequencing issue in Git. A commit gets rejected and causes a failed to push some refs to error because the remote branch contains code that you do not have locally. What this means is that your local git repository is not compatible with the remote origin.

Here is an abstraction of what incompatibility looks like in Git:

A -- B -- C -- D (on the remote)
A -- B -- E (on your local machine)

Based on the above, your local machine is missing commits C and D. Meanwhile, you are trying to slot in your commit – E – between B and C on the remote.

Before Git lets you proceed, you will need to integrate the remote changes into your local repository. This step will fix any incompatibility issues and ensure that your version is up to date with the remote.

How can you fix ‘failed to push some refs to’ errors

Here are the scenarios that may cause the failed to push some refs error, and how to correct them:

1.Another developer pushed a commit to the same branch

The error in your terminal looks like this:

To [email protected]:sometest.git
! [rejected] your-branch -] your-branch (non-fast-forward)

When this occurs, the head sits at different positions on the same code timeline, and Git does not know how to handle it. This is because the origin repository is ahead of where you currently are. To fix this issue, run git pull on your local repository. This should allow you to push to origin again.

git pull origin [your-branch]
git push origin [your-branch]

2. You got a ‘master (non-fast-forward)’ error with a ‘failed to push some refs to’ error

A git fast-forward happens when the ref pointer gets moved forward in the commit history. However, if your code diverges before it reaches the latest commit, it can cause the non-fast-forward issue and lead to a failed to push some refs to error.

To solve this issue, you can pull with the --rebase flag. --rebase will let you move your intended files to commit over to the latest pull code.

Here is how to pull with --rebase:

git pull --rebase origin [branch]

3. You got a ‘master (fetch first)’ error with a ‘failed to push some refs to’ error

When this occurs, someone has pushed to the branch before you. Git wants you to pull first before you can push your committed changes.

To prevent the loss of your work during the pull, you can stash your local changes.

The common suggested fix is to use --force flag to push through the local changes. However, it is good practice to avoid using the --force flag as it can cause inconsistency issues. Instead, use --rebase to move the ref heads and update your local repository without causing a divergence in the remote repository.

Using --force to try and fix the failed to push some refs to error will only result in more errors in the long run. This occurs because --force uses a brute force method that puts your current code and its ref head as the source of truth.

As a result, the changes in the remote can be overwritten by what you have pushed, removing any features or updates that other developers may have committed.

Only use --force if you are comfortable with features not on your local being overwritten with what you’ve currently got. Use the --force flag if you are confident that your local repository in its current state is correct.

How to prevent ‘failed to push some refs to’ errors

To prevent failed to push some refs to errors in Git, it is good practice to avoid having multiple developers work on the same branch simultaneously. Instead, use feature branches that merge into a master branch or something equivalent.

If you get a failed to push some refs to error, the main thing to do is git pull to bring your local repo up to date with the remote. Avoid employing the --force flag when using git pull and prevent other developers’ accidental overwrites of committed features.

Use the --rebase flag instead to avoid other errors from occurring while fixing your original failed to push some refs to error.

Kubernetes Troubleshooting with Komodor

We hope that the guide above helps you better understand the troubleshooting steps you need to fix the failed to push some refs to error.

Keep in mind that this is just one of many Git errors that can pop up in your K8s logs and cause the system to fail. Due to the complex and distributed nature of k8s,
the search for the root cause of each such failure can be stressful, disorienting, and time-consuming.

This is why we created Komodor, which acts as a single source of truth (SSOT) to streamline and shorten your k8s troubleshooting processes. Among other features, it offers:

  • Change intelligence: Every issue is a result of a change. Within seconds we can help you understand exactly who did what and when.
  • In-depth visibility: A complete activity timeline, showing all code and config changes, deployments, alerts, code diffs, pod logs, etc. All within one pane of glass with easy drill-down options.
  • Insights into service dependencies: An easy way to understand cross-service changes and visualize their ripple effects across your entire system.
  • Seamless notifications: Direct integration with your existing communication channels (e.g., Slack) so you’ll have all the information you need, when you need it.

  • Festool ka 65 ошибка 9
  • Ferrum tm 8420a ошибка е01
  • Ferroli ошибка а01 а 01 на газовом котле
  • Ferroli ошибка f35 как исправить
  • Ferroli котел ошибка а06