[HOW TO] Committing Code Using Intellij IDEA
This is a blogging version of the guildeline on committing code to GitHub repository. The GitHub version is available here . You are welcomed to clone/fork and use them as your team’s guildeline.
Committing Code using Intellij IDEA
This demonstration uses the Intellij IDEA Ultimate, version 2020.1. If you have already clone code, your IDE interface should look similar to this. Other Jetbrain IDEs, such as PyCharm, WebStorm, have very similar interface, so that you can use this tutorial if you are using other JetBrain IDEs.
1. Create a new branch
- Click the current branch (in this case, it is master )
- On the popped window, click the + New Branch
- Enter the name of your new branch.
- You can see now you are in dev branch.
2. Edit in the new branch
Edit code in the new branch.
3. Git Commit
Remember you are in the new branch while committing the code.
- Start committing code by clicking the commit button in the Git toolbox.
- Edit the commit message and add changed files on the popped window.
You can directly commit the code to the local repository and push to GitHub by clicking the button on the right side of Commit .
Github Integration with IntelliJ IDEA
Github is the most popular and one of the biggest repositories among the software community. It has various useful features that development teams are able to work together on the same project and also able to create new versions in the project without disrupting the current versions. So, keeping your project in a repository is needed.
There are so many ways to add the IntelliJ project to the Github repository. Today I’ll describe how to add your IntelliJ project to the git repository by using command lines.
Step 1
- Go to your Git account and create a new git repository.
Step 2
- Copy the newly created repository path
Step 3
- Cd to your project directory or you can do the below steps.
- Go to the location where you want to put the project.
Step 4
- Right-click on the folder and click “Git Bash Here” and type git<space>clone<space>paste the copied git URL and press “Enter”.
- After press enter, a new file will create with the git files and the same name that we add for our git repository.
Step 5
- Go to the original IntelliJ project folder and copy the files you want to add to GitHub and paste it into the newly cloned folder.
Step 6
- Type the command as git<space>add<space>. in the git bash.
Step 7
- Type the command as git<space>commit<space>-m<space>”git message; ex- initial commit” in the git bash.
Step 8
- Type the command as git<space>push in the git bash.
- And the GitHub login page will automatically display when you are doing this for the first time.
Step 9
- Give your GitHub login credentials and click “Login”
- Sometimes you may ask for the username and password again. Then give your GitHub username and password.
Step 10
- After the git push has been done, check your git repo whether committed codes have been added or not.
Apart from the above commands, there may be some other commands to add the IntelliJ project to Github.
Sharing your project on GitHub — The multi-step approach
Creating a Local Repository First and Sharing it to GitHub Later
The first approach we looked at assumed that you want to do everything in a single step. However, sometimes you want to create a local Git repository for your project well before you publish it publicly on GitHub.
Let’s assume you have a more complex project than Hello World and that you’re still in the process of writing the code. You don’t want to publish your project on GitHub just yet, but you do want to enable source control for it as you want to do small commits locally while you evolve the code.
Creating a Local Repository
You can check that your project isn't under version control by checking if you can see your Git tool window with ⌘9 (macOS), or Alt+9 (Windows/Linux). If you can't see the Git tool window, your project is not yet a Git project.
To use Git as the version control for an IntelliJ IDEA project, go to VCS > Enable Version Control Integration and select Git from the drop-down menu.
IntelliJ IDEA will now create a Git repository in the root directory of the project. We also now have access to the Git tool window with ⌘9 (macOS), or Alt+9 (Windows/Linux).
If you open this, you can click on the Console tab to see the Git commands that have been run and their result, or you can switch to the visual Log tab. You can now also see that there's a .git folder in your project, either from the Project Window ⌘1 (macOS), Alt+1 (Windows/Linux), or you can use IntelliJ IDEA’s terminal with ⌥F12 (macOS), or Alt+F12 (Windows/Linux) to list the project’s files.
Now you’ve enabled Git, but you 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 version control. Let’s select which files we want to be in version control, and make our first commit.
Making Your First Commit Locally
You can open the commit window using ⌘K (macOS) Ctrl+K (Windows/Linux). 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 your Preferences/Settings ⌘, (macOS), or Ctrl+Alt+S (Windows/Linux) and then search for Use non-modal commit interface.
If you open up the unversioned files list in this Commit window you can see all the files in your project are listed because none of them have been added to Git yet. You 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.
In this example, there are two directories that we don’t want to add to Git because they’re build directories. We do want to add the gradle wrapper directory, the source, and the files in the root of my project. If we open up the .idea folder, we 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, you can add all the other settings files to Git.
Add a description for this commit describing what functionality these changes do. When you commit this, you get a balloon saying this was successful. When you go back to the Git window with ⌘9 (macOS), or Alt+9 (Windows/Linux) the Log tab shows us this commit. You can see the files that were changed in this commit and the commit message. You can hide the Git window by pressing ⌘9 (macOS), or Alt+9 (Windows/Linux) again.
Creating a Repository on GitHub
So far you have been committing all these changes to your local Git repository. If you open the Log tab again with ⌘9 (macOS), or Alt+9 (Windows/Linux), you 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.
You can use IntelliJ IDEA to create a local Git repository and then share the project on GitHub by going to VCS > Share project on GitHub in the menu.
This displays the Share Project on GitHub dialog. Here you can give your GitHub repository a name, choose if you want it to be private, change the Remote (we recommend you don't), and give your project a description. Project names must be unique in your GitHub repository and follow the GitHub guidelines.
Maybe Required — Authenticating with GitHub
If you're not authenticated with GitHub you will see an additional Add Account link which has different options:
We'll focus on the top two options in this tutorial. Firstly, if you select Log in via GitHub, a window will open in your default browser asking you to log in to your GitHub account and authenticate it with IntelliJ IDEA.
Alternatively, you can select Log in with Token to open the Add GitHub account dialog. Here when you press Generate a window will open in your default browser asking you to log in to your GitHub account, and then you can generate a token for use in IntelliJ IDEA. You can follow the instructions on GitHub to do this. Once you have generated the token you can paste it back into the dialog to authenticate with GitHub.
Both these methods achieve the same result in that they allow IntelliJ IDEA to authenticate with GitHub.
When you press Enter or click 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.
Sharing a Project on GitHub
If you go back to IntelliJ IDEA, you can see the Git Log has been updated to show that the remote origin, is also at this commit. When you expand the Remote branches you 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.
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.
Name already in use
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Настройка Git и GitHub в Intellij IDEA
1. Добавить аккаунт GitHub в Intellij IDEA
1.1 Создать access token

Перейди в настройки GitHub -> Developer Settings -> Personal access token -> Generate new token

Оставьте только scope’ы: repo, workflow, read:org и gist.
Появится токен. Обязательно скопируйте его, потому что после того, как вы закроете страницу, он пропадёт!
1.2 Добавить аккаунт в Intellij IDEA
Зайдите в Intellij IDEA. Там File->Settings->Version Control->GitHub.

Там уже нажмите Ctrl+N(на Mac Cmd+N)->Login with token. И просто вставьте ваш скопированный токен в поле. Add account. Поздравляю, вы добавили GitHub аккаунт!
2.1 Скачать проект с GitHub
Для того чтобы клонировать проект, достаточно зайти в File->New->Project from Version Control.

Теперь достаточно выбрать проект и нажать Clone.
2.2 Сделать Commit
Достаточно нажать Git->Commit. Откроется вкладка Commit.

В Unversioned Files находятся файлы не добавленные в staging area. Там можно их добавить, чтобы они попали в следующий коммит. В Changes можно убрать файлы, которые не должны попасть в следующий коммит.
Когда файлы выбранный, можно написать сообщение для коммита и сделать его, нажав кнопку Commit.
2.3 Сделать Push
Это можно сделать из той же вкладки, нажав Commit and Push, после чего файлы загрузятся на удалённый репозиторий.
Так же это можно сделать перейдя Git->Push

В открывшемся окне можно выбрать необходимые коммиты и запушить их на удалённый репозиторий.
2.4 Загрузить через Fetch
Fetch безопасен всегда, поэтому его можно использовать когда угодно. Он просто загружает все изменения с удалённого репозитория, не делая merge с локальным репозиторием. Т.е. загруженные изменения не применятся, а останутся в отдельных ветках, расходящихся с вашими на последнем запушеном коммите.
Подходить, если вам нужно сделать Merge с изменениями из-вне вручную.
2.5 Загрузить через Pull
Pull работает только, если можно сделать fast-forward merge для веток с одинаковыми названиями в удалённом репозитории и в локальном.

В окне можно выбрать ветку, которую надо обновить из удалённого репозитория. Если удалённых репозиториев несколько, то их тоже можно выбрать.
Так же там можно добавить специальные опции, но они требуют отдельного объяснения.