Не получается подключить GitHub к Intellij IDEA

Пробовал переустанавливать и гит и идею. Всё равно идёт эта «бесконечная загрузка»
Отслеживать
задан 21 мар в 13:26
Dmitry Dmitriev Dmitry Dmitriev
0
Сортировка: Сброс на вариант по умолчанию
Знаете кого-то, кто может ответить? Поделитесь ссылкой на этот вопрос по почте, через Твиттер или Facebook.
- git
- intellij-idea
- github
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.10.27.43697
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Фишки IDEA. Часть 3 — теперь с Git
IntelliJ IDEA — фактически основной инструмент наших разработчиков. Года полтора назад мы публиковали собрание полезных фишек IDEA. С тех пор прошло много времени, а мы насобирали новую подборку — теперь уже для тех, кто только начинает работать в IDEA с Git. Кому интересно — добро пожаловать под кат.
Снова рассказываем по мотивам внутреннего митапа.

Ссылки на предыдущие части:
IntelliJ IDEA хороша тем, что при настройке проекта сама автоматически интегрируется с Git и поддерживает большую часть функциональности, добавляя к ней свои мелкие “плюшки”. Их же можно получить, работая с Git напрямую или через консоль. Но зачастую сделать это в IDE удобнее. К примеру, в IDEA намного проще разбираться с конфликтами, используя трехоконный интерфейс, нежели делать то же самое в git-овой консоли.
Ниже мы собрали несколько фишек, которые наши коллеги посчитали особенно удобными.
Выбираем быстрый метод работы с Git-репозиторием
Постоянно переключаться между IntelliJ IDEA и браузером, ходить в GitHub, чтобы что-то поменять или поправить, неудобно. Гораздо удобнее и, что удивительно, быстрее делать через IDE.
IDEA позволяет быстро переключаться между ветками и даже выполнять Rebase или Merge через меню в правом нижнем углу. Причем, субъективно переключение в IDEA работает в большинстве случаев быстрее, нежели то же самое изменение ветки из консоли. Все благодаря тому, что IDE умеет видеть разночтения между коммитами и ветками, позволяя быстрее индексировать эти файлы.
Из контекстного меню IDEA доступны все стандартные методы работы с Git. И здесь хочется сделать один акцент относительно переключения между ветками. IDEA умеет запоминать воркспейс в привязке к определенной ветке и восстанавливать его после возвращения на нее же (открывать все те файлы, что были открыты при работе над этой веткой, вплоть до восстановления настроек редактора и форматирования). Переключаясь обратно, вы как бы возвращаетесь в точку, где остановились.
По умолчанию эта опция включена, но не для всех она удобна. Ее можно отключить (или наоборот включить) в настройках.

Откладываем изменения на полку (Shelve)
В прошлой подборке фишек мы уже вспоминали про Shelve. Это аналог git stash, который позволяет не смешивать контексты при переключении между задачами. Но тогда мы не раскрывали подробностей, почему использовать его удобнее, чем git stash.
Предположим, к моменту переключения на новую задачу у нас есть некоторые изменения, которые еще рано коммитить. Чтобы не потерять предыдущие изменения, мы можем положить их “на полку” (shelve). Сделать это можно с помощью CTRL + SHIFT + H через окно Git.

После выполнения этой команды контекст откатывается к последнему коммиту, а изменения остаются на локальном диске в patch-файле. При изымании изменений с полки (unshelve) правки применяются к текущей ветке проекта.

Изменения, которые не были закоммичены, автоматически отправляются на полку. Полок может быть несколько. Подробности от разработчика есть здесь.
Главное отличие IDEA shelve от git stash в том, что последний по умолчанию работает по принципу стека — то, что в него попало последним, будет изъято первым. Это не всегда удобно. А с разных полок изменения можно брать в произвольном порядке.
Плюс реализации shelve именно в IDEA в том, что инструмент позволяет расшарить коллеге изменения, лежащие на полке. При этом создается патч, который можно отправить по почте или через мессенджер. Это удобно, например во время рефакторинга. Поправленную функцию можно быстро перекинуть коллеге, и он сможет применить его на своей задаче. Это немного нарушает рабочий процесс, но для небольших изменений на стадии автотестирования такое допустимо. Так что если разобраться, штука эта очень полезная.
Ищем историю изменений в Git
В IDEA Git History показывает в табличной форме историю всех изменений. Представление это не идеально, но намного удобнее, нежели в консоли.
Инструмент помогает делать код-ревью, сравнивая текущую ветку с каким-либо коммитом — IDEA подсвечивает внесенные правки. Так можно, например, сравнивать коммит с мастер-веткой.

С помощью истории изменений можно также объединить несколько коммитов в один. Для этого достаточно выделить последние коммиты, откатить их по одному, а затем разом вернуть. В итоге они окажутся в одном дополнительном коммите.
Кстати, из истории изменений выбранные коммиты можно откладывать на полку (в любом порядке). Восстанавливать с полки их также можно произвольно.
Коммитим в несколько репозиториев
Предположим, у вас был репозиторий кода с проектом А и другой репозиторий под смежный проект — B. Но при добавлении новой функциональности у вас появилась общая библиотека и вы ее вынесли в отдельный репозиторий. При исправлении этого общего кода иногда надо поправить что-то в проектах А и B. Несколько IDE для этого открывать неудобно. Гораздо проще добавить все проекты в IDEA и создать для них новую общую ветку, которая позволит в дальнейшем все действия производить сразу в трех репозиториях.
Естественно, одновременные действия возможны только в общие ветки. IDEA даже предупредит, если ветки в проектах не будут совпадать. Проблема этой киллер-фичи только в том, что на рабочей станции должно хватить памяти для двух или трех проектов — 10 Гб на практике оказывается мало, чтобы адекватно срабатывали поиски, индексирование и прочие “бытовые” вещи.
Ориентируемся в новом для себя проекте
В окне Git есть вкладка Local changes, которая показывает последние измененные файлы. Вкладка доступна, только если в Settings -> Version Control -> Commit отмечен пункт Use non modal committing interface. Правда, в этом режиме скрываются разночтения между файлами. В целом некоторым этот режим кажется более удобным — раньше он был единственным в IDEA.

На этом пока все. Если вам есть, чем поделиться с нашими коллегами, пишите в комментариях.
Статья написана по материалам митапа, который проводил Александр Козачук, Максилект.
P.S. Мы публикуем наши статьи на нескольких площадках Рунета. Подписывайтесь на нашу страницу в VK или на Telegram-канал, чтобы узнавать обо всех публикациях и других новостях компании Maxilect.
Hetty38 / gitIdea.txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| Работа с Git через IDEA |
| ———————————— |
| Добавление проекта с нуля |
| ———————————— |
| *будем работать с gitHub , создадим на нем новый репозиторий : |
| в настройках создания указать Initialize with a Readme |
| add gitignore : java (предопределены настройки для java проекта) |
| *Сlone or download -> копируем ссылку на репозиторий |
| *Открываем Idea, в меню выбираем Check out from Version of Control |
| Host — github.com |
| Auth type — password |
| Login — inozemtsev32 |
| paswrd — 11********** |
| press clone! |
| Would you like to create an Intellij Idea project — yes |
| Выбираем дальше по схеме |
| *в .gitignore в список игнорируемых форматов добавим |
| *.iml |
| .idea/* |
| *В правом верхнем углу нажимаем commit changes,пишем комментарий. |
| *Можно сразу сделать сommit и push, а можно просто коммит — |
| сохранить локально. |
| *создадим /src и в нем java class. Соглашаемся с добавлением слежки git |
| Вручную это можно сделать кликнув на файл и нажав git -> add |
| Если делать это через консоль, то каждое изменение в файле надо add’ить |
| *Если внести изменения через сайт, а потом там же внести некие |
| изменения через IDE будет конфликт. При пуше делаем наживаем merge==> |
| accept theirs, yours или сделть merge |
| ————————————— |
| Добавление уже существующего проекта |
| ————————————— |
| *создадим репозиторий без readme, к которому мы подключимся |
| *В меню : VCS-> import into version control -> create git repository |
| *cоздаем .gitignore |
| *нижимаем правой кнопкой на рабочее поле: |
| git -> git remotes -> add -> берем ссылку с гита, когда мы создали |
| проект она у нас появилась |
| *делаем комит и пуш |
| *можно создать reame.md на сайте и |
| потом в IDE сделать пул в правом верхнем углу |
Set up a Git repository
When you clone an existing Git repository or put an existing project under Git version control, IntelliJ IDEA automatically detects if Git is installed on your computer. If the IDE can’t locate a Git executable, it suggests downloading it.
IntelliJ IDEA supports Git from the Windows Subsystem for Linux 2 (WSL2), which is available in Windows 10 version 2004.
If Git is not installed on Windows, IntelliJ IDEA searches for Git in WSL and uses it from there. Also, IntelliJ IDEA automatically switches to Git from WSL for projects that are opened when you use the \\wsl$ path.
If you need to manually configure IntelliJ IDEA to use Git from WSL, go to the Version Control | Git page of the IDE settings Control+Alt+S , click the Browse icon in the Path to Git executable field, and select Git from WSL via the \wsl$ path, for example, \\wsl$\debian\usr\bin\git .
Check out a project from a remote host (git clone)
IntelliJ IDEA allows you to check out (in Git terms, clone ) an existing repository and create a new project based on the data you’ve downloaded.
- To start cloning a Git repository, do one of the following:
- If the version control integration is already enabled, go to Git | Clone .
- If the version control integration is not enabled yet, go to VCS | Get from Version Control . Alternatively, go to File | New | Project from Version Control .
- If no project is currently open, click Get from VCS on the Welcome screen.
- In the Get from Version Control dialog, specify the URL of the remote repository you want to clone or select one of the VCS hosting services on the left. If you are already logged in to the selected hosting service, completion will suggest the list of available repositories that you can clone.

- Click Clone . If you want to create a project based on the sources you have cloned, click Yes in the confirmation dialog. Git root mapping will be automatically set to the project root directory. If your project contains submodules, they will also be cloned and automatically registered as project roots.
- In the Trust and Open Project »? project security dialog, select the way you want to open the project: Trust Project or Preview in Safe Mode .
- When you import or clone a project for the first time, IntelliJ IDEA analyzes it. If the IDE detects more than one configuration (for example, Eclipse and Gradle), it prompts you to select which configuration you want to use. If the project that you are importing uses a build tool, such as Maven or Gradle, we recommend that you select the build tool configuration. Select the necessary configuration and click OK .
The IDE pre-configures the project according to your choice. For example, if you select Gradle , IntelliJ IDEA executes its build scripts, loads dependencies, and so on.
Put an existing project under Git version control
You can create a local Git repository based on the existing project sources.
Associate the entire project with a single Git repository

- Open the project that you want to put under Git.
- Press Alt+` to open the VCS Operations Popup and select Enable Version Control Integration . Alternatively, go to VCS | Enable Version Control Integration .
- Choose Git as the version control system and click OK . The entire project will then be associated with a single Git directory, so there is no need to add each file to the Git directory individually.
- After VCS integration is enabled, IntelliJ IDEA will ask you whether you want to share project settings files via VCS. You can choose Always Add to synchronize project settings with other repository users who work with IntelliJ IDEA.
If there is no Enable Version Control Integration option available in the VCS Operations Popup , it means that Git version control is already enabled for the project.
Associate different directories within the project with different Git repositories
- Open the project that you want to put under Git.
- Go to VCS | Create Git Repository .
- In the dialog that opens, specify the directory where a new Git repository will be created. Git does not support external paths, so if you choose a directory that is outside your project root, make sure that the folder where the repository is going to be created also contains the project root.
- If you are creating multiple Git repositories inside the project structure, repeat the previous steps for each directory.
After you have initialized a Git repository for your project, you need to add project files to the repository.
Add files to the local repository
- In the Commit tool window Alt+0 , expand the Unversioned Files node.
- Select the files you want to add to Git or the entire changelist and press Command Alt A or choose Add to VCS from the context menu. You can also add files to your local Git repository from the Project tool window: select the files you want to add, and press Command Alt A or choose Git | Add from the context menu.
When Git integration is enabled in your project, IntelliJ IDEA suggests adding each newly created file under Git, even if it was added from outside IntelliJ IDEA. You can change this behavior in the Version Control | Confirmation page of the IDE settings Control+Alt+S . If you want certain files to always remain unversioned, you can ignore them.
If you attempt to add a file that’s on the .gitignore list, IntelliJ IDEA will suggest force-adding it. Clicking Cancel in the confirmation dialog only cancels force-adding ignored files – all other files will be added to the Git repository.
Exclude files from version control (ignore)
Sometimes you may need to leave certain files unversioned. These can be VCS administration files, artifacts of utilities, backup copies, and so on. You can ignore files through IntelliJ IDEA, and the IDE will not suggest adding them to Git and will highlight them as ignored.
You can only ignore unversioned files, that is, files that you see in the Unversioned Files changelist. If a file is added to Git but not committed, you can right-click it in the Changes view and choose Rollback .
Git lets you list ignored file patterns in two kinds of configuration files:
- .git/info/exclude file. Patterns listed in this file only apply to the local copy of the repository. This file is created automatically when you initialize or check out a Git repository.
- One or more .gitignore files in the VCS root directory and its subdirectories. These files are checked into the repository so that the ignore patterns in them are available to the entire team. Therefore, it is the most common place to store the ignored file patterns. If there is no .gitignore file in the VCS root directory, you can right-click anywhere in the Project tool window, choose New | File , and type .gitignore in the New File dialog. To create a .gitignore file in Windows Explorer, create a file named .gitignore. and Windows will rename it automatically to .gitignore .
Add files to .gitignore or .git/info/exclude
- Decide what kind of Git configuration file you are going to use to ignore files. If in doubt, use .gitignore .
- Locate the unversioned file or folder you want to ignore in the Changes view or in the Project tool window. File colors in these views help you identify the status of the file.
- Right-click the selection and choose Git | Add to .gitignore or Git | Add to .git/info/exclude . File colors in these views help you identify the status of the file.
If you need to exclude files by a certain pattern or type, you can edit the .gitignore or .git/info/exclude file directly. See .gitignore patterns format.
If you want ignored files to be also displayed in the Changes view, click on the toolbar and select Show Ignored Files .
Add a remote repository
If you created a Git repository based on local sources, you need to add a remote repository to be able to collaborate on your Git project, as well as to eliminate the risks of storing your whole codebase locally. You push changes to a remote repository when you need to share your work and pull data from it to integrate changes made by other contributors into your local repository version.
If you have cloned a remote Git repository, for example, from GitHub, the remote is configured automatically, and you do not have to specify it when you want to sync with it. The default name Git gives to the remote you’ve cloned from is origin .
For more information about sharing project settings for different project formats, refer to Share project settings through VCS.
Define a remote
- Create an empty repository on any Git hosting, such as Bitbucket or GitHub. You can create a repository on GitHub without leaving IntelliJ IDEA: see Share a project on GitHub.
- Invoke the Push dialog when you are ready to push your commits by selecting Git | Push from the main menu, or press Command Shift K .
- If you haven’t added any remotes so far, the Define remote link will appear instead of a remote name. Click it to add a remote.
- In the dialog that opens, specify the remote name and the URL where it will be hosted, and click OK .
Add a second remote
In some cases, you also need to add a second remote repository. This may be useful, for example, if you have cloned a repository that you do not have write access to and are going to push changes to your own fork of the original project. Another common scenario is that you have cloned your own repository, which is somebody else’s project fork, and you need to synchronize with the original project and fetch changes from it.
- Go to Git | Manage Remotes . The Git Remotes dialog will open.
- Click the Add button on the toolbar or press Alt+Insert .
- In the dialog that opens, specify the remote name and URL and click OK .
- To edit a remote (for example, to change the name of the original project that you have cloned), right-click the remote branch in the Branches pane of the Git Log tool window and select Edit Remote from the context menu. You can also edit a remote from the Push Dialog by clicking its name.
- To remove a repository that is no longer valid, right-click it in the Branches pane of the Git Log tool window, and select Remove Remote from the context menu.
Learn more from this video: