Как связать github и intellij idea

Обновлено: 30.04.2024

In this blog, we’re going to look at how to share code that we’ve written on our local machine to a repository on GitHub.

This blog post covers the same material as the video with some additional tips and tricks. This provides an easy way for people to skim the content quickly if they prefer reading to watching, and to give the reader/watcher code samples and links to additional information.

There are a few ways to use IntelliJ IDEA to publish code that we’ve written on GitHub. In this blog, we will go over two approaches. The first is the quickest where you create your local and remote repository in one step. The second approach is multi-step which can be used when you want to create a local Git repository for your project separately from publishing any code publicly on GitHub.

Sharing Your Project on GitHub (Quick Approach)

Let’s assume we’ve created an IntelliJ IDEA project containing the code we want to share on GitHub. In this tutorial, we use a sample Hello World application that we know works because we’ve seen it run successfully. It’s not currently set up with any source control, which we can see in IntelliJ IDEA because there’s no option for opening a Git window, and if we list the project’s files in the Terminal window, we can see there’s no .git folder in the project. We can use IntelliJ IDEA to share this project on GitHub, we can go to the VCS menu and select Share project on GitHub.

Share Project on GitHub

If we’re not already logged in to GitHub via IntelliJ IDEA, we’ll be shown a log in dialog where we can enter our GitHub username and password. This also provides the option to log in using a token from GitHub, but even if we don’t select that option, if we log in with our username and password here IntelliJ IDEA will generate a GitHub token and use that to log in. If you don’t already have a GitHub account, you can use the Sign up for GitHub link in IntelliJ IDEA to create one. If you log in with your username and password, and have two-factor authentication enabled for GitHub, IntelliJ IDEA will pop up an additional dialog asking you to input your authentication code.

Tip: if you have multiple GitHub accounts, you can add your GitHub accounts by going to the IDE Preferences -> Version Control -> GitHub. Use the add button to add your accounts.

Once we’re successfully logged in, IntelliJ IDEA will ask us what we want to call the repository that we’re about to create on GitHub. This defaults to the project name, but we can pick any name for this repository, as long as it follows GitHub’s guidelines. For my Hello World project, I will call our repository hello-world-demo, as repositories have to have a unique name and I’m sure there’s already a repository called hello-world on my GitHub account. You can make this repository private if you like. I like to make my repositories public, unless there’s a compelling reason to make them private. You can rename the remote if you like, but I will accept the default here. I will also add a description too. This isn’t mandatory, but it helps people who want to understand what the project is for.

Share Project on GitHub Window

When we press Enter or click Share, IntelliJ IDEA will go ahead and create that repository on our GitHub profile. The IDE will ask us which files we want to put into this first commit. We could commit everything, but generally we don’t need to add the .gradle folder (if we’re using the Gradle wrapper), and we don’t need to add the build folder, which is where IntelliJ IDEA puts the compiler output like class files.

Add Files for Initial Commit

Everything else looks good to commit, we’ll use the default commit message and click Enter to commit it.

Under the covers, IntelliJ IDEA is creating a local Git repository for the project and then pushing it to your GitHub profile as a new repository with the details we just entered. When this process is finished, IntelliJ IDEA will pop up a balloon and we can click on the link to see the repository in GitHub in a browser. We can see the repository, the code, the commit message, and the description.

Shared on GitHub Bubble

Shared on GitHub Browser

Sharing Your Project on GitHub (Multi-step Approach)

The first approach assumed we want to do everything in a single step. Often we’ll want to create a local Git repository for our project well before we want to publish our code publicly on GitHub.

Let’s assume we have a more complex project than Hello World and that we’re still in the process of writing the code. We don’t want to publish our project on GitHub just yet, but we do want to enable source control for it as we want to do small commits locally while we evolve the code. We often want to save our project’s progress each step of the way, for example, once the tests are passing. So, first, we will create a local Git repository for this IntelliJ IDEA project.

We start with a project that is not currently under any source control, so there’s no Git or VCS tool window. To use Git as the version control for an IntelliJ IDEA project, go to the VCS menu and select Enable Version Control Integration.

Enable Version Control Integration

IntelliJ IDEA supports multiple version control systems, but for this example we want to choose Git. IntelliJ IDEA creates a Git repository in the root directory of the project. We also now have access to the Git tool window. If we open this, we can see the Console tab which shows the Git commands that have been run and their result, or we can switch to the visual Log tab. Using IntelliJ IDEA’s terminal to list the project’s files, we can also see that we now have a .git folder in the root of our project.

Now we’ve enabled Git, but we haven’t added anything to source control yet. We can see that our files are shown in red, which means as far as Git is concerned, these are new files that are not yet added to Git, so they’re not in source control. Let’s select which files we want to be in source control, and make our first commit.

We can open the commit window using Ctrl+K on Windows/Linux or ⌘K on macOS. The tutorial uses the Commit Tool Window, which was added in IntelliJ IDEA 2020.1. If you’re still using the old commit dialog, you can switch to the commit tool window in Preferences -> Version Control -> Commit -> Use non-modal commit interface.

If we open up the unversioned files list in this commit window we can see all the files in our project are listed because none of them have been added to Git yet. We probably don’t want to add everything to Git, there are some directories and files, like build output files, that we don’t need to put under source control. Seeing all the files in a single list like this might not be helpful, so we could opt to group the files, for example by directory or module.

Group by Directory

With this view I can see there are two directories that I don’t want to add to Git, because they’re build directories. I do want to add the gradle wrapper directory, my source, and the files in the root of my project. If I open up the .idea folder, I can see all IntelliJ IDEA’s settings files. Each team will have their own idea of which settings should be saved into source control, if any. IntelliJ IDEA automatically adds a .gitignore file to this directory with default folders and files to exclude from source control. We could add other files to this .gitignore file if there are other specific IDE settings that we don’t want to include. However, I’m going to add all the other settings files to Git.

Add Versioned Files

Add a description for this commit describing what functionality these changes do. When we commit this, we get a balloon saying this was successful. When we go back to the Git window, the Log tab shows us this commit. We can see the files that were changed in this commit and the commit message. We can hide the Git window by pressing Alt+9 or ⌘9 again.

So far we’ve been committing all these changes to our local Git repository. If you open the Log tab, we can see this project only has local branches, which means all the code and the commit history is only saved on this local computer. Once you finished setting up your project and are ready to share it and its history publicly on GitHub, go to Git -> GitHub -> Share Project on GitHub.

Share Project on GitHub Alternative

We recommend not waiting too long to push your project to GitHub since putting the project on a remote server like GitHub means that the code is safely backed up to another location.

If you’re already logged in to GitHub via IntelliJ IDEA, you don’t need to re-authenticate. We need to give the repository a name, this needs to be a unique repository name for the GitHub account it will live in. We can rename the remote here if we like, or leave it as origin . We can optionally add a description to help others understand what this project is. When we press Enter or Share, IntelliJ IDEA will create a new repository on GitHub under the account and push this code to that repository. The balloon notification shows when this is complete, so we can click on the link and see the new repository on GitHub in a browser. We can see the code on the project, and the three commits that we made locally are now available on GitHub.

If we go back to IntelliJ IDEA, we can see the Git Log has been updated to show that the remote, origin, is also at this commit. When we expand the Remote branches we can see the master branch under the origin remote. This shows us everything has been successfully pushed to GitHub, and that IntelliJ IDEA is also up to date with all the information from the GitHub remote.

Origin and Master Brances

In this blog, we learned two ways to create a GitHub repository and local Git repository for an existing IntelliJ IDEA project.

You can clone a repository that you want to contribute to directly from IntelliJ IDEA and create a new project based on it.

From the main menu, choose Git | Clone . The Git menu is available when you have set up a Git repository for your project. Until then, this menu is VCS .

In the Get from Version Control dialog, choose GitHub on the left.

Specify the URL of the repository that you want to clone. You can select a repository from the list of all GitHub projects associated with your account and the organization that your account belongs to.

In the Directory field, enter the path to the folder where your local Git repository will be created.

Click Clone . If you want to create a project based on these sources, click Yes in the confirmation dialog. IntelliJ IDEA will automatically set Git root mapping to the project root directory.

Share a project on GitHub

You can add a remote GitHub repository for a project you are developing locally, so that others can view it or contribute to it.

Open the project you want to share.

From the main menu, choose Git | GitHub | Share Project on GitHub .

If you have already registered your GitHub account in IntelliJ IDEA, connection will be established using these credentials.

If you have not registered your account in IntelliJ IDEA, the Login to GitHub dialog opens. Specify your access token or request a new one with your login and password.

When connection to GitHub has been established, the Share Project on GitHub dialog opens. Specify the new repository name, the name of the remote , and enter a description of your project.

You can select the Private option if you do not want to allow public access to your repository for other GitHub users.

Click Share to initiate a new repository and upload project sources to it.

Jump to the GitHub version of a file

You can jump from IntelliJ IDEA to the GitHub version of a file. IntelliJ IDEA detects which branch is currently active as well as the latest revision of the file, and opens the GitHub copy of the selected file in the corresponding commit in your web browser. If you are opening the GitHub file version from the editor, the file will be also automatically scrolled to the current line.

Select a file in the editor or in the Project view, and choose Open on GitHub from the context menu or from the Ctrl+Shift+A popup. The remote version of the file will open in the browser.

If the file points to more than one remote, you will be prompted to select the appropriate repository.

To be able to retrieve data from a repository hosted on GitHub, or share your projects, you need to register your GitHub account in IntelliJ IDEA.

If you do not want to specify your credentials each time you sync with a remote, or push your commits, you can configure IntelliJ IDEA to save your account information (see Configure a password policy).

Register an existing account

Press Ctrl+Alt+S to open the IDE settings and select Version Control | GitHub .

Do one of the following:

If you already have a token, click the Use Token link and paste it there.

If you want to obtain a new token, enter your login and password. If you have two-factor authentication enabled, you will be asked to enter a code that will be sent to you by SMS or through the mobile application. See Creating a personal access token for more details on GitHub tokens.

The token must have the repo , the gist and the read:org scopes enabled in your account permissions (see Understanding scopes).

Create a new GitHub account

Press Ctrl+Alt+S to open the IDE settings and select Version Control | GitHub .

Click Add account , and in the dialog that opens, click Sign up for Github .

Register your account on the Sign up for GitHub page that opens.

Return to the IntelliJ IDEA settings and specify your credentials.

Manage multiple accounts

You can use multiple GitHub accounts in IntelliJ IDEA: for example, a personal account to work on an open-source project, and a corporate account for your main job.

Press Ctrl+Alt+S to open the IDE settings and select Version Control | GitHub .

Use the button to add as many accounts as you need.

(Optional) To set an account as a default one for the current project, select it and click . If a default account is set, IntelliJ IDEA will not ask you to select an account you want to use when you share your project on GitHub, rebase a fork, create a pull request, or create a gist.

If you cannot view pull requests in the IDE, or you get an error when you log in to a GitHub account and perform any git operation, refer to the Operations Against a GitHub Repository Are Failing article for troubleshooting tips.

Подружим Git с Intellij IDEA - 1

По сложившейся традиции, приветствую вас, будущие Senior Software Engineers. Сегодня поговорим о логическом продолжении моей статьи про Гит. Также я советую прочесть материал о стратегиях ветвления, который я опубликовал ранее. В статье про Гит я описал, как работать с ним в командной строке, а сегодня покажу, как сделать все это в Intellij IDEA. В начале своего пути как разработчика я пользовался именно командной строкой и думал, что мне незачем использовать UI для этого дела. Ведь все понятно и так… Но это было ровно до того момента, пока я не начал использовать Гит в Intellij IDEA… Хочу сказать сразу, что я буду описывать личный опыт работы. Есть несколько вариантов решения одних и тех же задач через Intellij IDEA, и если вы знаете, как сделать лучше то, что я опишу в статье — пишите в комментарии, обсудим.

Необходимые вводные:

  1. Прочесть, повторить и понять статью про гит. Это поможет быть уверенным, что все уже настроено и готово к работе
  2. Установить Intellij IDEA.
  3. Выделить часик личного времени для полного усвоения.

Клонируем проект локально

  1. Если есть уже гитхаб аккаунт и хочется что-то потом запушить, лучше сделать форк проекта к себе и клонировать свою копию. Как сделать форк — я описывал в этой статье в главе пример the forking workflow.
  2. Клонировать с моего репозитория и проделать все локально без возможности все это дело запушить на сервер. Ведь это же будет мой репозиторий))

Копируем адрес проекта:

Открываем Intellij IDEA и выбираем Get from Version Control:

Копируем вставляем адрес на проект:

Вам предложат создать Intellij IDEA проект. Принимаем предложение:

Так как нет системы сборки, и это не входит в задачу статьи, выбираем Create project from existing sources:

Первый взгляд на Intellij IDEA как на гит UI

Присмотритесь еще раз внимательно на клонированный проект: уже там можно получить много информации о системе контроля версий. Первое — это Version Control панель в нижнем левом углу. В ней можно найти все локальные изменения и получить список коммитов (аналог git log). Перейдем в лекцию Log. Присутствует некая визуальная составляющая, которая помогает понять, как именно шел процесс разработки. Например, видно, что создавалась новая ветка с коммитом added header to txt, который после влился в мастер-ветку. Если нажать на коммит, в правом углу можно увидеть всю информацию о коммите: всех изменениях и его метаданных. Более того, можно посмотреть, какие были сделаны изменения. Тем более что там же был разрезолвлен конфликт. Это IDEA тоже отлично показывает. Если нажать два раза на файл, который был изменен за этот коммит, увидим, как резолвили кофликт: Заметно, что справа и слева были два варианта одного файла, который нужно было смержить в один. А посредине — результат, который в итоге получился. Когда в проекте множество веток, коммитов и пользователей, которые работают в проекте, необходимо поискать отдельно по ветке (branch), пользователю (user) и дате (date): И последнее, что я хочу объяснить перед началом работы — это то, как же понять, в какой ветке мы находимся. Даю минуту на поиск… нашли? Сдаетесь? :D В правом нижнем углу есть кнопка Git: master, где после Git: показано, на какой ветке находится сейчас проект. Если нажать на кнопку, можно проделать множество полезных вещей: перейти на другую ветку, создать новую, переименовать существующую, и так далее.

Работа с репозиторием

Полезные горячие клавиши

  1. ctrl + t — получить последние изменения с удаленного репозитория (git pull).
  2. ctrl + k — сделать коммит/посмотреть все изменения, которые есть на данный момент. Сюда входят и untracked, и modified файлы (смотри мою статью про гит, там это описано) (git commit).
  3. ctrl + shift + k — это команда для создания пуша изменений на удаленный репозиторий. Все коммиты, которые были созданы локально и еще не находятся на удаленном, будут предложены для пуша (git push).
  4. alt + ctrl + z — откатить в конкретном файле изменения до состояния последнего созданного коммита в локальном репозитории. Если в левом верхнем углу выделить весь проект, то можно будет откатить изменения всех файлов.

Что мы хотим?

Получить все изменения на текущий момент в основной ветке (master, например).

На базе этой основной создать отдельную для своей работы.

Реализовать новую функциональность.

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

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

Получить изменения с удаленного сервера?

Подружим Git с Intellij IDEA - 13

Я добавил описание в README новым коммитом и хочу эти изменения получить. Предлагается выбор между мерджем и ребейзом в случае, если были сделаны изменения и в локальном репозитории и на удаленном. Выбираем мерж. Вводим ctrl + t: В результате, видно как изменился README, т.е. изменения из удаленного репозитория подтянулись, и в правом нижнем углу можно посмотреть все детали тех изменений, которые пришли с сервера.

Создать новую ветку на основе master

Переходим в правый нижний угол и нажимаем на Git: master, выбираем + New Branch.

Оставляем галочку Checkout branch и пишем имя новой ветки. Для меня это будет readme-improver.

Подружим Git с Intellij IDEA - 16

После этого Git: master сменится на Git: readme-improver.

Имитируем параллельную работу

Чтобы конфликты появились, их кто-то должен создать :D Я через браузер отредактирую README новым коммитом и таким образом сымитирую параллельную работу. Мол кто-то во время моей работы сделал изменения в том же файле, что и я, что приведет к конфликту. Я удалю слово “полностью” из 10 строки.

Реализовать свою функциональность

Задача стоит в том, чтобы поменять README и добавить описание к новой статье, то есть то, что работа в гите идет через Intellij IDEA. Добавляем это: Изменения выполнены, теперь можно создать коммит. Нажимаем горячую клавишу ctrl + k, получим: Прежде чем создать коммит, нужно внимательно посмотреть на то, что предлагается в этом окне. Я специально добавил стрелочек, куда посмотреть. Там много интересных вещей. В секции Commit Message пишем текст коммита, и чтобы он создался, нужно нажать кнопку Commit. Я так и не нашел, как бы так сделать это горячей клавишей, так что если кто-то найдет — пишите, я буду очень рад. Пишем, что README изменился и создаем коммит. В результате в левом нижнем углу всплывает оповещение, в котором будет имя коммита:

Проверить, не изменилась ли основная ветка

  1. accept yours — принять только изменения из readme-improver.
  2. accept theirs — принять только изменения из master.
  3. merge — самому выбрать, что нужно оставить, а что убрать.
  1. Это изменения из readme-improver.
  2. Результат. Пока что там так, как было до изменений.
  3. Изменения из master ветки.

Запушить изменения на удаленный сервер

Следующий шаг — запушить изменения на удаленный сервер и создавать пул-реквест. Для этого просто нажимаем ctrl + shift + k, после чего получим: Слева будет список коммитов, которые не запушены на удаленный репозиторий, а справа будут все файлы, которые изменены. И все: нажимаем Push, и будет вам счастье :) При успешном пуше будет вот такое уведомление в нижнем правом углу:

Бонусная часть

Не хотел изначально добавлять создание пул-реквеста в статью, но получается не очень законченной из-за этого. Поэтому переходим на гитхаб репозиторий (если он ваш, конечно))) ) и видим, что гитхаб уже знает, что нам предложить: Нажимаем на Compare & pull request, после чего нажимаем Create pull request. Из-за того, что мы заблаговременно порешали конфликты, теперь при создании пул-реквеста, его сразу можно мержить: Вот и все, что я хотел вам рассказать в этот раз. Разумеется, я только открыл вам дверь и показал малую часть. Остальное уже по мере необходимости сами найдете. Традиционно приглашаю подписаться на мой GitHub аккаунт, где я выставляю проекты-наработки на разные технологии, которые использую на работе. У меня недавно было личное достижение — мой проект был оценен уже более чем сотней разработчиков. Это невероятное чувство радости, что то, что ты сделал, кто-то использует. И использует для пользы.

Чтобы импортировать ваш проект из системы контроля версий, нажмите кнопку Check out from Version Control на Welcome screen (приветственное окно IDEA), или в меню VCS (система контроля версий) на главной панели меню.

Руководство пользователя IntelliJ IDEA. Основы работы с системами контроля версий - 2

Если в вашем проекте есть файлы настройки сборки для Maven или Gradle, IntelliJ IDEA предложит вам использовать их для конфигурации.

Настройки системы контроля версий

Настройки системы контроля версий вашего проекта доступны в меню Settings → Version Control. Вы можете выбрать любую из директорий вашего проекта в качестве корневой для используемой вами системы контроля версий, а также поменять этот выбор в любое время. Также вы можете в любой момент отключить контроль версий.

Руководство пользователя IntelliJ IDEA. Основы работы с системами контроля версий - 3

Также, вы можете разные директории вашего проекта хранить в разных системах контроля версий, IntelliJ IDEA позволяет вам проводить все операции над ними одинаково.

Окно инструментов «изменения» и списки изменений

После того как вы подключили систему контроля версий на вашем проекте, вы можете видеть и управлять локальными изменениями с помощью окна инструментов Changes. Чтобы быстро его открыть, нажмите Alt + 9 (Cmd + 9 для Mac).

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

Всплывающее меню операций системы контроля версий

Если вам нужно запустить какую-то операцию системы контроля версий для выделенного файла, директории или даже для всего проекта, используйте всплывающее меню VCS operations по сочетанию клавиш Alt + Back Quote (одиночная левая кавычка, символ ') (Ctrl + V для Mac).

Отображение истории изменений

История изменений для файлов или директорий вашего проекта доступна из меню VCS operations, или из главной панели меню VCS → → Show History, или из контекстного меню → Show History.

Руководство пользователя IntelliJ IDEA. Основы работы с системами контроля версий - 6

Чтобы посмотреть изменения для конкретного фрагмента кода, используйте пункт Show History for Selection.

Аннотации

Аннтоации доступны как из всплывающего меню, так и из главного и контекстного меню. Они позволяют вам видеть кто и когда поменял каждую конкретную строку кода.

Руководство пользователя IntelliJ IDEA. Основы работы с системами контроля версий - 7

Вызвав панель аннотаций, вы увидете детальную информацию о соответствующем коммите.

Полезные клавиатурные сочетания

  • Добавить текущий список изменений в систему контроля версий Ctrl + K (Cmd + K для Mac)
  • Обновить проект Ctrl + T (Cmd + T для Mac)
  • Добавить выделенные файлы и директории в систему контроля версий Ctrl + Alt + A (Alt + Cmd + A для Mac)
  • Пометить выделенные файлы и папки как измененные (обновленные) Ctrl + Alt + E (Alt + Cmd + E для Mac)
  • Посмотреть изменения (доступно в окне инструментов Changes) Ctrl + D (Cmd + D для Mac)
  • Переместить изменения в другой список изменений (доступно в окне инструментов Changes) F6
  • Залить ваши локальные изменения в удаленную систему контроля версий Ctrl + Shift + K (Cmd + Shift + K для Mac)

Варианты сохранения изменений

Когда вы добавляете ваши изменения в систему контроля версий, IntelliJ IDEA позволяет вам производить самые разные операции: поменять список изменений в который вы их добавляете, объеденить изменения с уже добавленными, используя Amend commit, переформатировать измененный код, оптимизировать импорты, убедиться что инспекция кода не выдает никаких предупреждений, обновить информацию о копирайте, или даже загрузить ваши изменения на удаленный ftp сервер.

Игнорируемые файлы

Настроить список игнорируемых файлов можно в меню Settings → Version Control, или с помощью соответствующей кнопки в окне инструментов Changes.

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

Ветви

С помощью IntelliJ IDEA вы можете легко создавать, переключаться, объединять, сравнивать и удалять ветви кода. (только в Git и Mercurial). Чтобы посмотреть список существующих ветвей или создать новую, используйте либо Branches из главного или контекстного меню, или всплывающее меню VCS operations, или элемент управления на правой стороне панели статуса.

Руководство пользователя IntelliJ IDEA. Основы работы с системами контроля версий - 10

Для разных систем контроля версий IntelliJ IDEA производит все операции одновременно, так что вы не должны переключаться между ними.

Shelves, stashes, и patches

Меню Shelves и Stashes помогает вам спрятать некоторые локальные изменения без добавления их в систему контроля версий. Нужно это для того, чтобы переключиться на ту версию файлов что хранится в системе контроля версий и потом иметь возможность вернуться назад к вашим локальным изменениям. Различаются они тем, что Shelves поддерживается самой IntelliJ IDEA и хранятся они локально у вас, а Stashes хранятся в системе контроля версий. Patches позволяет вам сохранить некоторый набор изменений в виде файла, который можно передать по электронной почте или выложить на общедоступный диск и потом применить к коду. Это полезно если вы работаете удаленно, без постоянного подключения к системе контроля версий, но все равно должны передавать ваши изменения другим членам проекта.

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

Читайте также: