Перейти к содержимому

Как поменять default ветку git

  • автор:

Как переименовать ветку по умолчанию “default” в Git и GitLab

Git и техническое сообщество в целом недавно перешли на использование термина main для описания новой ветки по умолчанию. Другие платформы для размещения кода, такие как GitHub, внесли изменения и GitLab, как еще одна общедоступная платформа хостинга git, также внесла изменения в версии 14.0 для самостоятельных версий, выпущенных 22 июня 2021 года.

Ранее GitLab внесла изменение для пользователей GitLab.com. Переход от master к main не должен быть пугающим, на самом деле изменение имени основной ветки git-репозитория с main на master может быть довольно быстрым и простым процессом. Вам даже не нужно создавать новый репозиторий git.

Ветка по умолчанию

Если вы используете ветку main в качестве имени ветки Git по умолчанию, то, возможно, вы подумываете о переименовании своей ветки в существующих проектах, на master, как это было привычнее. Но как это сделать?

Здесь мы поговорим об использовании GitLab для переименования главной ветви в master. Репозитории Git являются одним из самых популярных инструментов отслеживания исходных текстов, используемых сегодня, и переименование «дефолтной ветки». Многие начинающие разработчики хотят следовать лучшим практикам и тенденциям и сменить свой git repo master на main или наоборот. Переименовав нашу ветвь git в новую основную ветвь, мы можем получить “main/master” в качестве нашей новой ветви. Мы также можем обновить наше соединение для отслеживания.

Переименование вашей локальной ветки

Сразу оговорюсь, что вы можете переименовать свою ветку так как вам это хочется сделать или с учетом принятых норм в вашей команде разработки. Далее мы будем рассматривать пример переименования «master» branch to «main».

Чтобы переименовать вашу локальную «главную» ветку на вашем компьютере, вам просто нужно запустить простую команду с одним вкладышем. Это обновит вашу локальную основную ветку, но не удаленную ветку. Позже нам также нужно переименовать удаленную основную ветку и изменить имя ветки по умолчанию в репозитории git.

$ git branch -m master main

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

$ git status

On branch main Your branch is up to date with ‘origin/master’. nothing to commit, working tree clean

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

На данном этапе мы обновили текущую локальную ветку, но не обновили наш удаленный репозиторий. Наше существующее отслеживающее соединение по-прежнему указывает на master и это не привело к удалению переименованной ветки.

Переименование ветки Master

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

Пока мы находимся в нашей «дефолтной» ветке, как и раньше, мы можем отправить эту новую ветку в удаленный репозиторий.

$ git push -u origin main

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

$ git status

On branch main Your branch is up to date with ‘origin/main’. nothing to commit, working tree clean

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

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

Это позволит нам избежать сообщения ошибке при удалении нашей старой основной ветки в нашем репозитории git. Перейдите в свой репозиторий на GitLab.com или в собственный экземпляр GitLab и перейдите в «Настройки» -> «Репозиторий». Вверху страницы настроек есть ветка Default.

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

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

Новую ветку нужно сделать protected, а старую ветку unprotect. Это соответсвено позволит удалить вашу старую ветку.

$ git push origin — delete master

$ git push origin — delete master

To gitlab.hatchet.com.au:

bud/seo.git — [deleted] master

Как изменить основную(default) ветку в gitlab

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

Отслеживать
2,382 2 2 золотых знака 8 8 серебряных знаков 20 20 бронзовых знаков
задан 28 апр 2022 в 14:21
15 5 5 бронзовых знаков
какая версия gitlab у вас?
29 апр 2022 в 5:34

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

введите сюда описание изображения

В gitlab версий 12.8 — 14.4 это делается в меню Settings -> Repository

Отслеживать
ответ дан 29 апр 2022 в 5:39
Aleksey Vaganov Aleksey Vaganov
2,382 2 2 золотых знака 8 8 серебряных знаков 20 20 бронзовых знаков

    Важное на Мете
Похожие

Подписаться на ленту

Лента вопроса

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.10.27.43697

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Изменение ветви по умолчанию

Если в репозитории есть несколько ветвей, можно настроить любую ветвь как ветвь по умолчанию.

Кто может использовать эту функцию.

People with admin access for a repository can change the default branch for the repository.

About changing the default branch

You can choose the default branch for a repository. The default branch is the base branch for pull requests and code commits. For more information about the default branch, see «About branches.»

Note: If you use the Git-Subversion bridge, changing the default branch will affect your trunk branch contents and the HEAD you see when you list references for the remote repository. For more information, see «Support for Subversion clients» and git-ls-remote in the Git documentation.

You can also rename the default branch. For more information, see «Renaming a branch.»

Prerequisites

To change the default branch, your repository must have more than one branch. For more information, see «Creating and deleting branches within your repository.»

Additionally, you need to have admin access to a repository to change the default branch.

Changing the default branch

  1. On GitHub.com, navigate to the main page of the repository.
  2. Under your repository name, click

Settings. If you cannot see the «Settings» tab, select the

Screenshot of a repository header showing the tabs. The

dropdown menu, then click Settings.

Manage Git branches

In Git, branching is a powerful mechanism that allows you to diverge from the main development line, for example, when you need to work on a feature, or freeze a certain state of a code base for a release, and so on.

In PyCharm, all operations with branches are performed in the Git Branches popup. To invoke it, in the main window header, click the Git widget with the name of the branch that is currently checked out:

Git widget

You can also manage branches and perform batch operations with multiple branches in the Branches pane of the Git tool window.

Create new branch

Create a new branch from current branch

  1. In the Branches popup, choose New Branch or right-click the current branch in the Branches pane of the Git tool window and choose New Branch from ‘branch name’ .
  2. In the dialog that opens, specify the branch name, and make sure the Checkout branch option is selected if you want to switch to that branch. Once you start typing a name for your new branch, PyCharm will suggest relevant prefixes based on the names of existing local branches. The new branch will start from the current branch HEAD.

Create a new branch from selected branch

  1. In the Branches popup or in the Branches pane of the Git tool window select a local or a remote branch that you want to start a new branch from and choose New Branch from Selected .
  2. In the dialog that opens, specify the branch name, and make sure the Checkout branch option is selected if you want to switch to that branch.

Create a new branch from selected commit

  1. In the Log view, select the commit that you want to act as a starting point for the new branch and choose New Branch from the context menu.
  2. In the dialog that opens, specify the branch name, and make sure the Checkout branch option is selected if you want to switch to that branch.

Rename branches

  1. In the Branches popup or in the Branches pane of the Git tool window, select the branch you want to rename and choose Rename .
  2. In the dialog that opens, change the branch name to the one you need.

To copy the name of a branch, hover over the branch and press Control+C .

Mark branches as favorites

If you have many branches, you may want to see only your favorite ones. The main branch is marked as a favorite by default. Favorite branches are always displayed at the top of the Branches popup and in the Branches pane of the Git tool window.

favourite branch

  • To mark a branch as a favorite, in the Branches popup, hover over the branch name, and click the star outline that appears on the left: Alternatively, select the branch you want to mark as favourite and press Space . You can also select a branch in the Branches pane of the Git tool window and click on the toolbar.

While searching for a particular branch and navigating the list of branches, press Control+F to move the focus back to the search field.

Group branches

In the Branches popup, PyCharm keeps branches in three nodes:

  • Recent branches node shows up to five recently checked-out branches.
  • Local branches node lists all local branches.
  • Remote branches node shows all remote branches available after the latest fetch.

Also, PyCharm automatically groups branches by prefix and stores them in expandable lists.

Branches grouped by prefix in the Branches popup

In order for branches to be grouped, prefixes in branches’ names should be separated with forward slashes / . For example, jd/2023.1 .

If you do not want your branches to be grouped by prefix, click in the upper-right corner of the Branches popup and then deselect the Group by Prefix option to disable it.

Group by Prefix option in the Branches popup

Check out branches (git-checkout)

If you want to work on a branch created by someone else, you need to check it out to create a local copy of that branch.

To make sure you have a full list of remote branches, click in the Branches popup:

the Fetch icon

Check out a branch as a new local branch

  1. In the Branches popup or in the Branches pane of the Git tool window, select a branch that you want to check out locally from Remote Branches , or Common Remote Branches if your project has several roots and synchronous branch control is enabled, or from Repositories | Remote Branches if it is disabled.
  2. Choose Checkout from the list of actions.

А new local branch will be created, checked out and set to track the origin remote branch.

It can happen that you already have a local branch with the same name as a remote branch you want to check out. Depending on the situation, here is how you can finish the checkout process:

  • If no commits will be lost, and the local branch already tracks the remote, PyCharm automatically resets the local branch to the remote branch and then checks it out.
  • If the local branch contains commits that can be lost because of the reset, PyCharm will offer you to:
    • Drop Local Commits : PyCharm will drop your local commits, reset the local branch, and change tracking.
    • Rebase onto Remote : PyCharm will rebase your local branch onto the remote branch, keep your local commits, reset the local branch, and change tracking.

    Switch between branches

    When multitasking, you often need to jump between branches to commit unrelated changes.

    1. In the Branches popup or in the Branches pane of the Git tool window, select the branch that you want to switch to under Local Branches and choose Checkout from the list of available operations. For multi-repository projects, branches are automatically grouped by repositories. To check out the necessary branch, in the Branches popup, choose the repository first.
    2. What happens next depends on whether there are conflicts between your local changes that you have not committed yet, and the branch that you are going to check out:
      • If your working tree is clean (that means you have no uncommitted changes), or your local changes do not conflict with the specified branch, this branch will be checked out (a notification will pop up in the bottom-right corner of the PyCharm window).
      • If your local changes are going to be overwritten by checkout, PyCharm displays a list of files that prevent you from checking out the selected branch, and suggests choosing between Force Checkout and Smart Checkout . If you click Force Checkout , your local uncommitted changes will be overwritten, and you will lose them. If you click Smart Checkout , PyCharm will shelve uncommitted changes, check out the selected branch, and then unshelve the changes. If a conflict occurs during the unshelve operation, you will be prompted to merge the changes. For more information, refer to Resolve conflicts. If you want to clean your working copy using stash instead of shelve, go to the Version Control | Git page of the IDE settings Control+Alt+S and choose Shelve under the Clean working tree using setting.

    PyCharm saves your context (a set of opened files, the current run configuration, and breakpoints) provided that the Restore workspace on branch switching option is enabled in the Settings dialog Control+Alt+S under Version Control | Confirmation . When you switch to a branch, PyCharm automatically restores your context associated with that branch.

    Compare branches

    Compare a branch with the current branch

    If you want to check how a branch has diverged from the current branch, you can compare them.

    1. From the Branches popup or from the Branches pane of the Git tool window, select the branch that you want to compare with the current branch, and choose Compare with Current . A new tab will be added to the Git tool window listing all commits that exist in the selected branch and do not exist in the current branch. You can click the Swap Branches link to change which branch is considered as a base against which you are comparing the other branch.
    2. To see a list of all files that are different in the two branches, click Control+A : the Changed Files pane will list all files that contain differences.

    Compare a branch with the working tree

    Apart from comparing a branch with the current branch, you can compare it against the local state of the current branch. This is useful if you have local uncommitted changes.

    • From the Branches popup or from the Branches pane of the Git tool window, select the branch that you want to compare with the local working tree, and choose Show Diff with Working Tree . The Changes tool window that opens shows a list of all files that are different in the selected branch compared with the branch that is currently checked out:
      • Files that exist in the selected branch and are missing in the current branch are marked with grey.
      • Files that exist in the current branch but are missing in the selected branch are marked with green.
      • Files that contain differences between the selected and the current branch are marked with blue.

      You can click the Swap Branches link to change which branch is considered as a base against which you are comparing the other branch.

      • To review the differences within a specific file, select it and click on the toolbar, or press Control+D .
      • To apply the entire file contents to the current branch, click . For more information, refer to Apply separate files.

      Watch this video to get a better view on how to compare changes to your branch:

      Delete branches

      After you have integrated the changes from a feature branch into the main line of development, you can delete the branch you do not need anymore.

      1. Check out a branch that you are going to use for further work.
      2. In the Branches popup or from the Branches pane of the Git tool window, right-click the branch you want to delete and choose Delete .

      After you have deleted a branch, a notification will be displayed in the bottom-right corner from which you can restore the deleted branch:

      deleted branch notification

      If the branch contained commits that have not yet been merged to its upstream branch or to the current branch, it will still be deleted immediately (equivalent to the git branch —D or git branch —delete —force command), but the notification will also contain a link allowing you to view the unmerged commits.

      If the deleted branch was tracking a remote branch, there will also be a link in this notification to remove the remote branch.

      If you’ve closed the notification and later decide you want to restore a deleted branch, the link will be available in the Notifications tool window until you restart PyCharm.

      Configure synchronous branch control

      If you have a multi-rooted repository, you can configure PyCharm to perform all branch operations (such as checkout, merge, delete, and so on) simultaneously on all roots as if it were a single repository.

      1. Press Control+Alt+S to open the IDE settings and then select Version Control | Git .
      2. Select the Execute branch operations on all roots option (note that this option is only available if your project has multiple roots).

      If an operation fails at least in one of the repositories, PyCharm prevents branches from diverging by suggesting that you roll back this operation in the repositories where it was successful.

      If you check out a branch only on one of the roots, PyCharm will show the Branches have diverged warning in the Branches popup. It means that the root projects are on different branches.

      In case you want to proceed, either ignore this warning or disable the Execute branch operations on all roots option. If you still want to execute branch operations on all roots simultaneously, check out the branch with the same name in the rest of the repositories manually.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *