Шпаргалка по git-flow
Эта шпаргалка показывает основные способы использования операций git-flow.
Общие замечания
- Git flow предоставляет превосходную командную строку со справкой и улучшенными выводом. Внимательно читайте его, чтобы знать, что происходит.
- Клиент для macOS/Windows Sourcetree — отличный GUI для Git — также поддерживает git-flow
- Git-flow основан на слиянии. Для слияния веток фич не используется rebase.
Установка
- В первую очередь вам нужна рабочая установка git
- Git flow работает на macOS, Linux и Windows
macOS
$ brew install git-flow-avh
$ port install git-flow-avh
Linux
$ apt-get install git-flow
Windows (Cygwin)
$ wget -q -O — —no-check-certificate https://raw.github.com/petervanderdoes/gitflow-avh/develop/contrib/gitflow-installer.sh install stable | bash
Вам потребуется wget и util-linux для установки git-flow.
Подробные инструкции по установке git flow смотрите на git flow wiki.
Приступая к работе
Git flow нужно инициализировать, чтобы настроить его для работы с вашим проектом.
Инициализация
Для начала использования git-flow проинициализируйте его внутри существующего git-репозитория:
git flow init
Вам придётся ответить на несколько вопросов о способах именования ваших веток.
Рекомендуется оставить значения по умолчанию.
Фичи
- Разработка новых фич для последующих релизов
- Обычно присутствует только в репозиториях разработчиков
Начало новой фичи
Разработка новых фич начинается из ветки «develop».
Для начала разработки фичи выполните:
git flow feature start MYFEATURE
Это действие создаёт новую ветку фичи, основанную на ветке «develop», и переключается на неё.
Завершение фичи
Окончание разработки фичи. Это действие выполняется так:
- Слияние ветки MYFEATURE в «develop»
- Удаление ветки фичи
- Переключение обратно на ветку «develop»
git flow feature finish MYFEATURE
Публикация фичи
Вы разрабатываете фичу совместно с коллегами?
Опубликуйте фичу на удалённом сервере, чтобы её могли использовать другие пользователи.
git flow feature publish MYFEATURE
Получение опубликованной фичи
Получение фичи, опубликованной другим пользователем.
git flow feature pull origin MYFEATURE
Вы можете отслеживать фичу в репозитории origin с помощью команды git flow feature track MYFEATURE
Создание релиза
- Поддержка подготовки нового релиза продукта
- Позволяет устранять мелкие баги и подготавливать различные метаданные для релиза
Начало релиза
Для начала работы над релизом используйте команду git flow release Она создаёт ветку релиза, ответляя от ветки «develop».
git flow release start RELEASE [BASE]
При желании вы можете указать [BASE] -коммит в виде его хеша sha-1, чтобы начать релиз с него. Этот коммит должен принадлежать ветке «develop».
Желательно сразу публиковать ветку релиза после создания, чтобы позволить другим разработчиками выполнять коммиты в ветку релиза. Это делается так же, как и при публикации фичи, с помощью команды:
git flow release publish RELEASE
Вы также можете отслеживать удалённый релиз с помощью команды
git flow release track RELEASE
Завершение релиза
Завершение релиза — один из самых больших шагов в git-ветвлени. При этом происходит несколько действий:
- Ветка релиза сливается в ветку «master»
- Релиз помечается тегом равным его имени
- Ветка релиза сливается обратно в ветку «develop»
- Ветка релиза удаляется
git flow release finish RELEASE
Не забудьте отправить изменения в тегах с помощью команды git push —tags
Исправления
- Исправления нужны в том случае, когда нужно незамедлительно устранить нежелательное состояние продакшн-версии продукта
- Может ответвляться от соответствующего тега на ветке «master», который отмечает выпуск продакшн-версии
git flow hotfix start
Как и в случае с другими командами git flow, работа над исправлением начинается так:
git flow hotfix start VERSION [BASENAME]
Аргумент VERSION определяет имя нового, исправленного релиза.
При желании можно указать BASENAME-коммит, от которого произойдёт ответвление.
Завершение исправления
Когда исправление готово, оно сливается обратно в ветки «develop» и «master». Кроме того, коммит в ветке «master» помечается тегом с версией исправления.
Рабочий процесс Gitflow Workflow
Git-flow — это устаревшая версия рабочего процесса Git, в свое время ставшая принципиально новой стратегией управления ветками в Git. Популярность Git-flow стала снижаться под влиянием магистральных рабочих процессов, которые на сегодня считаются предпочтительными для современных схем непрерывной разработки ПО и применения DevOps. Кроме того, Git-flow не слишком удобно применять в процессах CI/CD. В этой публикации приводится описание Git-flow для истории.
Что собой представляет Git-flow?
Git-flow — альтернативная модель ветвления Git, в которой используются функциональные ветки и несколько основных веток. Эта модель была впервые опубликована и популяризована Винсентом Дриссеном на сайте nvie. По сравнению с моделью магистральной разработки, в Git-flow используется больше веток, каждая из которых существует дольше, а коммиты обычно крупнее. В соответствии с этой моделью разработчики создают функциональную ветку и откладывают ее слияние с главной магистральной веткой до завершения работы над функцией. Такие долгосрочные функциональные ветки требуют тесного взаимодействия разработчиков при слиянии и создают повышенный риск отклонения от магистральной ветки. В них также могут присутствовать конфликтующие обновления.
Git-flow можно использовать для проектов, в которых запланирован цикл релизов и реализуется характерная для DevOps методика непрерывной поставки. В этом рабочем процессе используются понятия и команды, которые были предложены в рамках рабочего процесса с функциональными ветками. Однако Git-flow привносит новые специфические роли для разных веток и определяет характер и частоту взаимодействия между ними. Помимо функциональных веток в рамках этого рабочего процесса используются отдельные ветки для подготовки, поддержки и регистрации релизов. При этом вы по-прежнему можете пользоваться преимуществами рабочего процесса с функциональными ветками, такими как запросы pull, изолированные эксперименты и эффективное командное взаимодействие.
GitFlow: what is difference between release and master branches?
I’ve just took a look on this gitflow cheat sheet. I don’t understand the release branch. Could anybody tell me the difference between release and master branches?
15.8k 12 12 gold badges 51 51 silver badges 70 70 bronze badges
asked Oct 6, 2016 at 17:53
22.1k 43 43 gold badges 172 172 silver badges 377 377 bronze badges
Are there any recommendations around timing for merging release branch into master. I am not sure of whether release branch should be merged into master before the release into production or rather releasing into production from release branch and then merging into master. My release branch is sign-ed off already. If i merge this into master and deploy into production, then i wouldn’t tested that merged version. Ideally since my master is not being touched, then any merge from release into master should not produce any conflicts or any other surprise. However i am not sure what is the recommen
Feb 6, 2019 at 3:34
@AnujKhanna to avoid surprises is exactly why git-flow is recommended. There’s a cheat sheet attached to the description of the question, following it should keep you safe. Besides, I feel if I’m confident of merging a release branch to the master branch, it should be safe to merge into production as well.
Sep 6, 2020 at 14:04
4 Answers 4
The difference is in goals and process. A release branch is usually created when you are preparing for an upcoming release. When all your feature branches which are supposed to be released have already been merged to develop branch you create release branch off develop branch and commit only bug fixes or some configuration changes to it. In other words you try to make it as stable as it’s possible. When hopefully release branch is stable enough you merge it back to develop and master branches. The purpose of master branch is to always have the latest stable version of the project which can be deployed to production environment. You never commit directly to master branch, only merge to it from either release or hotfix branches. It is also possible to configure CI/CD tools to deploy to production on any update in master branch.
answered Oct 6, 2016 at 18:53
Alexey Andrushkevich Alexey Andrushkevich
6,162 4 4 gold badges 35 35 silver badges 49 49 bronze badges
Once all the features you want to have in your release are in develop, instead of «locking» develop to any new commit, you create the relase branch that will contains all the feature expected in your next release (and not in master since your whole release should be tested and would probably have some bugfix. ).
- In this branch you have only bug fixes, documentation etc. but no new feature
- your develop branch is not locked up, so new features for the next release can still be commited/push on develop and tested.
- release branch is perfect to be deployed on staging/pre-prod environment and let QA test your release.
- Once release branch is stable, you can merge it into master and go to prod. Master should always be stable and steady (if not you make hotfix).
You can have a look at these links for further explanations:
answered Oct 6, 2016 at 18:09
2,600 4 4 gold badges 29 29 silver badges 33 33 bronze badges
I think your question comes from a misunderstanding of GitFlow that I often see. So it is worth debunking it.
In GitFlow release branches are short-lived. They are used to prepare a release. The benefit of the release branch is it makes it possible for one team to polish the current upcoming release while another team continues working on features for the following release(s). In contrast the master branch lives forever.
In GitFlow you do not release to production environment from the release branch. That is not what the release branch is for. The misunderstanding probably comes from the name «release branch». The master branch must reflect actual production worthy releases. You merge your release branch into master and you then release (i.e. creating artifacts) for production environment from the master branch. Artifacts meant for production environment always originate from master branch in GitFlow. You cannot have artifacts in production environment from any other branch. In essence every merge into master is a new official release in the GitFlow model.
The release branch goes away again once the release is over (once you’ve merged it to master ) and I for one find it catastrophic to release into production environment from a branch which is deleted shortly thereafter.
The above seems to be controversial for some. But I think this is the classic GitFlow idea as described in the original paper. You’ll find some who actually create build artifacts out of their release branch and they then put that into production environment. When they see it works they’ll go back and merge it to master too. (or they’ll forget this step). I don’t think that is GitFlow.
A workflow where artifacts deployed into production environment are from another branch than master simply isn’t GitFlow. It may be a good workflow for some, it may have its advantages, but it ain’t GitFlow.
So in short this is classic GitFlow where you can clearly see the difference between a release branch and the master branch:
- Prepare release on a branch named release/ .
- When ready to ship : merge the release branch into master . Then delete your release branch (it no longer has a purpose).
- Tag master with a version number, for example 5.9.1 .
- Create deployable artifacts from the tag on master . You now have a release (potentially for production environment). You now test those artifacts in all your environments: test, staging, etc. If it fails testing (despite the testing you’ve done before you merged to master ) then you must accept that you now have a release 5.9.1 which goes in the wastebasket. Live with it!. You must then start over with a new release branch, for example release/5.9.2 .
- You can finally put the tested artifacts into production environment. If it turns out there’s a problem in the production environment with the new release (despite all the testing) then again you must create a new release. This means you start over with either a new release branch or you follow the hotfix workflow model.
As can be seen, in GitFlow once you merge to master you’ve probably already done a lot of testing so that the risk that the release created from master will fail in testing is slim.
Note that GitFlow of course doesn’t prevent you from creating artifacts from all the other branches than master and deploy them for testing purpose to any environment, except production environment.
Для чего нужна ветка release в gitflow
- Using bounded context for effective domain-driven design Domain-driven design helps organizations develop software focused on key business needs. But to do so, architects need to .
- Object-oriented vs. functional programming explained While plenty of developers entertain the idea of adopting a functional programming model, it’s important to first know exactly .
- The 5 SOLID principles of object-oriented design explained In this primer on SOLID, we’ll examine the five principles this development ideology embodies, the practices they encourage and .
- Positive vs. negative testing: Differences and examples Take an in-depth look at positive and negative testing. Learn how to use both to form the basis of a thorough testing approach .
- The 7 stages of the SDLC explained The development process can be broken into seven distinct phases that transform high-level plans into production-ready software. .
- Learn the phases of feature-driven development Learn how development teams can use the five phases of feature-driven development to put Agile principles into practice by .
- 6 best practices for a cloud-first strategy Adopting a cloud-first strategy requires careful consideration to ensure affordability and optimal performance. Implement a .
- Troubleshooting 7 common errors in AWS CloudFormation Errors can occur when an AWS developer builds a CloudFormation template, launches a stack or rolls back an update. Prevent and .
- Explore CASB use cases before you decide to buy CASB tools help secure cloud applications so only authorized users have access. Discover more about this rapidly evolving .
- EDR vs. EPP: What’s the difference? Endpoint detection and response tools and endpoint protection platforms offer similar security features. Which is better for your.
- Security updates from Google Cloud Next ’24 center on GenAI Google has infused Gemini into its security tools and while GenAI isn’t going to solve every security problem right away, its .
- Navigating cloud patch management: Benefits, best practices Bad actors use malicious code to exploit vulnerabilities, targeting on-demand systems and applications. Having an efficient .
- AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
- Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
- Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .