Pulling without specifying how to reconcile divergent branches is discouraged
Pulling without specifying how to reconcile divergent branches is discouraged
Git теперь ругается на git pull
Начиная с версии 2.27, git ругается на обычный pull примерно следующим содержанием:
Почитал пару ненавистников merge-commit’ов. Вот один из них. Ощущения интересные, будто говна поел.
Ну у меня все изменения в master через merge-request’ы, поэтому master(или уже main?) состоит только из merge-commit’ов.
Так уже не модно что ли? Все дружно адово rebase’ят при слиянии веток? Зачем решать очередные конфликты, если были merge’ы из master в отдельную ветку? Странные люди.
Ну, в проекте, где я примерно 60 активных бранчей с чудесными пересплитениями. Раньше хуже было, доходило до 200.
И да, я больше практически не мержу (кроме релиз бранчей и мастера).
master и только master!
Речь не о слиянии в master, а о слиянии master в другие ветки. Когда в левую ветку пару раз master тащат, а потом в обратную сторону делают. Там прямо какие-то узлы в истории появляются потом.
Вы тоже из тех, у кого на слово «магистр» встаёт? Бедные люди. Умственно бедные.
Я что-то пропустил или это таки разговор в контексте Билли и запрещенных барабанщиков, и теперь нужно использовать исключительно leader? 🙂
Черт, так это резюме теперь править надо? =(
В той статье вроде и не против слияний в принципе.
Я не понимаю эту наскальную живопись.
Ну, если вести линию до конца, то ты теперь не Master of Science, a Main of Science. 😉
И да, если следовать другому бреду blacklist → blocklist, то и black magic → block magic.
В общем, хотели как «лучше», а обосрались по полной.
А все потому, что мама не привела Колдуна 😉
И вообще, лучше играть в баскетбол, чем выпускать фальшивые деньги)
Кстати, на по-троллить: предлагаю ввести новую степень Slave of Science! 😀
Как выполнить слияние, если вы получаете сообщение об ошибке «Подсказка: у вас есть расходящиеся ветки, и вам нужно указать, как их согласовать».
Я работаю с 1 другим разработчиком, который создал ветку, которую нужно объединить с мастером.
Я получаю эту ошибку при попытке извлечь Git в сообществе Visual Studio (не Visual Studio Code) в репозиторий Bitbucket.
Если я пытаюсь нажать, он говорит: «Невозможно нажать, потому что ваша локальная ветвь находится за удаленной ветвью».
Я нашел различные вещи, которые обсуждают это, например
Но никто из них не объясняет, ПОЧЕМУ это происходит и что на самом деле делают действия.
Как я могу объединить то, что находится в другой ветке, с мастером, почему появляется это сообщение и какой эффект имеют все предложения в подсказках?
Как это часто бывает с запутанными вещами в Git, в этом есть некоторая история.
Первое, что нужно знать, это то, что git pull делает слишком много вещей. Ну, для некоторых людей (для меня) это слишком много; другим нравится, что он делает так много; но на самом деле он выполняет две работы, каждая из которых имеет свою отдельную команду Git:
Предполагая, что первый шаг выполнен успешно, git pull запускает вторую команду Git.
Причина, по которой вообще нужен шаг 2, достаточно проста: git fetch получает новые коммиты из какого-то другого репозитория Git, помещая эти новые коммиты в свой собственный репозиторий, где у вас теперь есть к ним доступ. Но тогда это остановки. Вы иметь доступ к новые коммиты, но на самом деле ничего не используется новые коммиты еще. Чтобы использовать новые коммиты, вам нужен второй шаг.
Однако здесь есть четыре возможности:
Возможно, вы не работали, и они не работали. У вас нет новых коммитов. Делать буквально нечего, и git merge ничего не делает.
Возможно, вы сделали какую-то работу, а они ничего не сделали; у вас нет новых коммитов; делать нечего и git merge опять ничего не делает.
Возможно, вы не работали, а они что-то делали. У вас есть новые коммиты. Совместить ваше отсутствие работы с их фактической работой легко, и git merge будет сокращать путь, если вы позволите.
Возможно, вы и они оба работали. У вас есть новые коммиты и, вы получили от них новые коммиты, и git merge должен использовать свои простые и глупые правила, чтобы объединить работу. Git не может использовать ярлыки здесь, и вы получите полномасштабное слияние.
Ярлык, который может использовать Git мая, — просто проверить их последний коммит, перетащив имя вашей ветки вперед. Команда git merge называет это быстрое слияние, хотя на самом деле слияние не используется. Этот вид не-на самом деле-слияния тривиален и, как правило, чрезвычайно безопасен: единственное, что может пойти не так, могу — это если их последний коммит на самом деле не работает должным образом. (В этом случае вы можете вернуться к более старой версии, которая делает это.) Таким образом, слияние «ускоренной перемотки вперед» особенно удобно: в нем нет сложных правил построчного слияния, которые могут пойти наперекосяк. Такое «слияние» нравится многим.
Иногда ярлык невозможен, а иногда некоторые люди не используют хотеть Git, чтобы воспользоваться ярлыком (по причинам, которые мы не будем здесь раскрывать, чтобы этот ответ был кратким или коротким для меня). Есть способ рассказать git merge не ищи ярлык, даже если можешь.
Итак, только для git merge это дает нам три возможности:
У команды git merge есть параметры, чтобы указать, что делать во всех случаях, кроме случая «нечего делать»:
Но подождите, есть еще
И независимо от того, сделаете вы это или нет, вы можете сливаться вашего коммита J с их коммитом L создать новый фиксация слияния M :
Команда git pull может выполнять такое перемещение:
Это возвращает нас к 2006 или 2008 году или около того.
На данном этапе разработки Git у нас есть:
Время продолжает идти вперед, и мы достигаем 2020-х годов.
1 Один реальный пример: я столкнулся с какой-то ошибкой, которая меня беспокоит. Я вношу изменения в заведомо неправильный код, но позволяю меня выполнять работу мой. Я совершаю этот ужасный взлом. Затем я жду, пока восходящий поток внесет изменения. Они делают, и я вношу новые коммиты. Если у них есть исправлено ошибка, я хочу уронить мое исправление, а не объединять или перебазировать его. Если они нет исправили ошибку, я хочу перебазировать свой хак (который может нуждаться или не нуждаться в некоторой настройке). Тест «исправили ли они ошибку» требует чего-то, что git pull не может быть протестировано само по себе.
2 Обратите внимание, что запуск аргументов git pull с не должен вызывать такую жалобу. Я до сих пор мало его запускаю, поэтому не совсем уверен, в чем была ошибка, но в первом или двух раундах реализации новой функции была ошибка, из-за которой git pull жаловался неуместно. Я считаю, что это исправлено в версии 2.35, и я почти уверен, что это исправлено в версии 2.36, которая должна выйти в ближайшее время.
Git warning: Pulling without specifying how to reconcile divergent branches is discouraged
Last updated on November 7, 2021 by Sal Ferrarello
As of Git version 2.27.0 running the command git pull will display the following message unless your Git configuration includes certain settings.
Short Explanation
Git wants us to choose how it should handle the situation where our remote branch (e.g. origin/develop ) is out of sync with our local branch ( develop ). Many people (myself included) feel the default way Git historically handled this situation was sub-optimal however changing the default behavior is a big deal. Instead Git has made it easy to modify the behavior and added this screen to remind you that you might want to change the default.
Short Fix
The short answer is yes, we do want to change the default behavior and we can do that by running the following from the command line.
The Problem We are Solving
When working with Git you have your local branch on your computer (e.g. develop ) and your remote branch (e.g. origin/develop ). Your remote branch typically lives somewhere like GitHub.
You’d like to have the same commits on your local branch and your remote branch, so it looks something like this.
(If viewing your Git branch as a list of commits like this seems unfamiliar, I suggest checking out my post on How to Improve Git Log)
Someone Else Adds a Commit
Both Add a Commit
Imagine the situation where someone else adds a commit to the remote branch (e.g. zyx911 gets added to origin/develop ) and at the same time we add a commit to our local branch (e.g. we add dg34mp to develop ).
Now when we run git pull Git says, “Whoa, hold on! I can’t add the zyx911 commit to our local branch because there is an extra commit on our local branch that doesn’t exist on the remote branch!” (a.k.a. I don’t know how to handle zyx911 ).
Note: This is the same situation I discuss in Git failed to push some refs.
Three Ways to Handle the Situation
Create a Merge Commit
Additionally, because we are merging these to different commits this is a common time to have merge conflicts.
Rebase our Local Commits
Rebasing is an important Git idea that deserves an entire post of its own but in broad strokes:
Rebasing takes our local commit ( dg34mp ) and temporarily removes it from our local branch, which makes it an easy fast-forward merge
then our commit ( dg34mp ) is added back to our local branch
however because the commit hash ( dg34mp ) is based on not only our changes but all the changes before it, the commit hash changes (here to 40r931 ). This is also a time that merge conflicts are common.
Don’t Do Anything By Default
Then we can explicitly tell Git to rebase our changes
or create a merge commit
Global Git Configuration
to our global Git configuration, typically found at
Pulling without specifying how to reconcile divergent branches is discouraged
Okay this time, I deleted everything in public_html in the server folder. \n
Consider a task as simple as attaching an invoice to an email and sending it to a particular user. It’s an incredibly common task, and yet, there are many, many steps involved. What should the invoice look like? How do you programmatically save it as a PDF? How do you attach it to an email? How might you test that the notification was properly sent?
If you’re interested, come along as I work on this very task for the Laracasts codebase. «,»path»:»\/series\/intricacies-of-sending-an-invoice»,»strippedBody»:»Consider a task as simple as attaching an invoice to an email and sending it to a particular user. It’s an incredibly common task, and yet, there are many, many steps involved. What should the invoice look like? How do you programmatically save it as a PDF? How do you attach it to an email? How might you test that the notification was properly sent?If you’re interested, come along as I work on this very task for the Laracasts codebase.»,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/intricacies-of-sending-an-invoice.png»,»large_thumbnail»:»https:\/\/laracasts.s3.amazonaws.com\/series\/thumbnails\/social-cards\/intricacies-of-sending-an-invoice.png»,»svgThumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/svg\/intricacies-of-sending-an-invoice.svg»,»slug»:»intricacies-of-sending-an-invoice»,»episodeCount»:5,»difficultyLevel»:»Advanced»,»customUrl»:null,»version»:null,»version_notes»:null,»complete»:1,»wallpaper»:»https:\/\/laracasts.nyc3.digitaloceanspaces.com\/series\/wallpapers\/Intricacies-of-Sending-an-Invoice.zip»,»archived»:0,»runTime»:»38m»,»taxonomy»:<"name":"Techniques","path":"https:\/\/laracasts.com\/browse\/techniques">,»hasChapters»:false,»isLarabit»:0,»isCreatorSeries»:0,»progress»:<"started":false,"completionPercentage":0,"episodesCompleted":0,"completed":false,"nextEpisodePosition":1>,»lastUpdated»:»Jan 27, 2022″>,<"id":151,"className":"Laracasts\\Series","title":"Reproduce Popular Web Components","body":"
This series is all about recreating the look and feel of popular or compelling web components that you might find around the web. From cool menu transitions, subtle UI interactions, or more complex animations, we’ll break it all down and recreate it from scratch. \r\n
Pulling without specifying how to reconcile divergent branches is discouraged
Okay this time, I deleted everything in public_html in the server folder. \n
Consider a task as simple as attaching an invoice to an email and sending it to a particular user. It’s an incredibly common task, and yet, there are many, many steps involved. What should the invoice look like? How do you programmatically save it as a PDF? How do you attach it to an email? How might you test that the notification was properly sent?
If you’re interested, come along as I work on this very task for the Laracasts codebase. «,»path»:»\/series\/intricacies-of-sending-an-invoice»,»strippedBody»:»Consider a task as simple as attaching an invoice to an email and sending it to a particular user. It’s an incredibly common task, and yet, there are many, many steps involved. What should the invoice look like? How do you programmatically save it as a PDF? How do you attach it to an email? How might you test that the notification was properly sent?If you’re interested, come along as I work on this very task for the Laracasts codebase.»,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/intricacies-of-sending-an-invoice.png»,»large_thumbnail»:»https:\/\/laracasts.s3.amazonaws.com\/series\/thumbnails\/social-cards\/intricacies-of-sending-an-invoice.png»,»svgThumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/svg\/intricacies-of-sending-an-invoice.svg»,»slug»:»intricacies-of-sending-an-invoice»,»episodeCount»:5,»difficultyLevel»:»Advanced»,»customUrl»:null,»version»:null,»version_notes»:null,»complete»:1,»wallpaper»:»https:\/\/laracasts.nyc3.digitaloceanspaces.com\/series\/wallpapers\/Intricacies-of-Sending-an-Invoice.zip»,»archived»:0,»runTime»:»38m»,»taxonomy»:<"name":"Techniques","path":"https:\/\/laracasts.com\/browse\/techniques">,»hasChapters»:false,»isLarabit»:0,»isCreatorSeries»:0,»progress»:<"started":false,"completionPercentage":0,"episodesCompleted":0,"completed":false,"nextEpisodePosition":1>,»lastUpdated»:»Jan 27, 2022″>,<"id":151,"className":"Laracasts\\Series","title":"Reproduce Popular Web Components","body":"
This series is all about recreating the look and feel of popular or compelling web components that you might find around the web. From cool menu transitions, subtle UI interactions, or more complex animations, we’ll break it all down and recreate it from scratch. \r\n
Источники информации:
- http://reddeveloper.ru/questions/kak-vypolnit-sliyaniye-yesli-vy-poluchayete-soobshcheniye-ob-oshibke-podskazka-u-vas-yest-raskhodyashchiyesya-vetki-i-vam-nuzhno-ukazat-kak-ikh-soglasovat-JXmVj
- http://salferrarello.com/git-warning-pulling-without-specifying-how-to-reconcile-divergent-branches-is-discouraged/
- http://laracasts.com/discuss/channels/code-review/git-pull-error-pulling-without-specifying-how-to-reconcile-divergent-branches-is-discouraged?page=1&replyId=773818
- http://laracasts.com/discuss/channels/code-review/git-pull-error-pulling-without-specifying-how-to-reconcile-divergent-branches-is-discouraged?page=1&replyId=773806