- Настройка Git в Intellij IDEA
- Создание локального репозитория git
- Intellij idea как настроить git
- Set up a Git repository
- Check out a project from a remote host (clone)
- Put an existing project under Git version control
- Associate the entire project with a single Git repository
- Associate different directories within the project with different Git repositories
- Add files to the local repository
- Exclude files from version control (ignore)
- Add files to .gitignore or .git/info/exclude
- Check project status
- Track changes to a file in the editor
- Add a remote repository
- Define a remote
- Add a second remote
Настройка Git в Intellij IDEA
Сегодня мы рассмотрим простой способ настройки Git в Intellij IDEA. Прочив это руководство вы сможете коммитить и пушить изменения в проекте на ваш репозиторий на GitHub.
1. Intellij IDEA нажимаем VCS -> Import into Version Control -> Create Git Repository
В появившемся окне выбираем корневой каталог проекта и нажимаем ОК
2. Идем на GitHub и создаем новый репозиторий с желаемым названием
3. Идем в закладку Changes (в нижнем левом углу Intellij IDEA) или с помощью комбинации клавиш Alt + 9 и нажимаем правой кнопкой мыши на файлах под названием Unversioned Files, далее в появившемся контекстном меню выбираем Add to VCS
4. В закладке Changes нажимаем правой кнопкой мыши на пункте Default и в появившемся контекстном меню выбираем Commit Changes
5. В появившемся окне в отделе Commit Message пишем вразумительный комментарий к коммиту, галочкой выбираем нужные для коммита файлы (или вовсе не трогаем отмеченные файлы) и жмем на кнопку Commit. Все, файлы закоммитились на локальный репозиторий.
6. Теперь закоммитим на удаленный репозиторий (мы его создавали в пункте 2). Для этого зайдите на страницу репозитория на github, например: https://github.com/username/reponame, где
username — ваш логин на github
reponame — название вашего репозитория
Теперь найдите на странице репозитория блок HTTPS clone URL и скопируйте ссылку в буфер обмена.
7. Теперь идем в закладку Terminal (в нижнем левом углу Intellij IDEA) и пишем следующие команды:
Источник
Создание локального репозитория git
У вас есть проект и вы хотите сохранить его на GitHub. Рассмотрим как сделать это из среды разработки IntelliJ IDEA.
Шаг 1: создадим локальный репозиторий на своем компьютере. Открываем свой проект в IntelliJ IDEA. Для инициализации локального git-репозитория в верхнем меню нажимаем пункт VCS ->Import into Version Control->Create Git Repository.
В открывшемся окошке выбираем путь где хотим инициализировать репозиторий (можно оставить по умолчанию) и нажимаем кнопку Ok:
После того как будет создан локальный репозиторий, внизу появится меню Version Control. Если меню не появилось, выбираем View->Tool Windows->Version Control:
Шаг 2: добавим файлы под версионный контроль. В окошке Version Control нас интересует вкладка Local Changes. В списке Unversioned Files находятся файлы, которые не отслеживаются git. Intellij IDEA выделяет их коричневым:
Выберем файлы, изменения в которых мы хотим отслеживать, вызываем контекстное меню и нажимаем кнопку Add to VCS:
Обычно это только java файлы. Конфигурационные и class файлы не следует добавлять в репозиторий.
После добавления, Main.java переместился в список Default Changelist — здесь находятся файлы отслеживаемые git, которые попадут под версионный контроль после коммита. Intellij IDEA выделяет только что добавленные файлы зеленым цветом:
Если проект уже находится под версионным контролем, то при добавлении нового файла, Intellij IDEA предлагает добавить его сразу же под версионный контроль:
Соглашаемся — жмем Yes.
Шаг 3: Коммит файлов. Наконец вы хотите сохранить состояние своего проекта в репозиторий git. Для этого делаем так называемый коммит, который создает снимок состояния (snapshot) проекта в данный момент. Выбираем Default Changelist, вызываем контекстное меню и жмем Commit:
В открывшемся окне заполняем поле Commit message — указываем какие изменения сделаны в этом коммите:
Состояние всех файлов, находящихся в Default Changelist сохраняется в снимке.
При изменении файла, который уже был закомичен, он опять попадает в Default Changelist, но теперь будет синего цвета.
Для того чтобы просмотреть все коммиты, перейдите во вкладку Log. Здесь можно увидеть всю информацию о сделанных коммитах: кто и когда сделал коммит, какие файлы были изменены.
Шаг 4: публикация проекта на GitHub. Наконец вы решили залить свой проект на Github. Для этого в верхнем меню нажимаем пункт VCS -> Import into Version Control -> Share Project on GitHub:
Шаг 5: Операция push. После публикации репозитория на Github вы сделали изменения в своем локальном репозитории, и хотите эти изменения добавить на GitHub. Для этого используется операция push: VCS->Git->Push.
Шаг 6: Операция pull. Если изменения в вашем локальном репозитории устарели и вы хотите подтянуть изменения с GitHub, используйте операцию pull: VCS->Git->Pull.
Источник
Intellij idea как настроить git
Use this page to specify the version control settings that will be applied to the directories of your project that are under Git control.
| Item | Description |
|---|---|
| Path to Git executable | |
| Test | Click this button to verify the path to the Git executable file. |
| Set this path only for current project | Select this option if you want to use different paths for different projects, and don’t want this setting to be applied globally. |
| Execute branch operations on all roots | |
| Commit automatically on cherry-pick | When you cherry pick a specific commit, the Commit Changes dialog is displayed. If the Commit automatically on cherry-pick option is selected, the selected commit is submitted silently on clicking the cherry-pick button , without displaying the Commit Changes dialog. |
| Add the ‘cherry-picked from ‘ suffix when picking commits pushed to protected branches | Select this option if you want to keep a reference to the original commit when cherry-picking a commit from a protected branch. By default, no suffix is added when cherry-picking a change. |
| Warn if CRLF line separators are about to be committed | |
| Warn when committing in detached HEAD or during rebase | Select this option if you want IntelliJ IDEA to display a warning when a commit is performed from a detached head or on rebase, as this may cause issues and code loss. |
| Explicitly check for incoming commits on remotes | If this option is enabled, IntelliJ IDEA will check if there are pending incoming commits that have not been fetched to your local repository, and will mark such branches in the Branches popup. Select how you want to IntelliJ IDEA to query the remote to check for incoming commits: Auto : IntelliJ IDEA will check for updates in the background if HTTP or Git protocol is used to access the remote. If SSH is used, this check will not be performed so that external authentication applications don’t popup unexpectedly. Always : IntelliJ IDEA will check for updates in the background even if SSH is used to access the remote. Never : IntelliJ IDEA will not query the remote for incoming commits, and a warning will be displayed in the Branches popup, allowing you to run the check manually. |
| Update method | Use this list to choose the strategy to synchronize your local repository with the remote storage. The selected method will be used when the push operation is rejected (if the Auto-updated if push of the current branch was rejected option is enabled), or when you invoke the Update Project operation. The following options are available: Merge : select this option to perform merge during the update. This is equivalent to running git fetch and then git merge , or git pull —no-rebase . Rebase : select this option to perform rebase during the update. This is equivalent to running git fetch and then git rebase , or git pull —rebase (all local commits will be put on top of the updated upstream head). |
| Clean working tree using | Select how you want uncommitted changes to be treated when you perform a project update: Stash : local changes will be saved to a git stash. This is useful if you need to apply patches with stashed changes outside IntelliJ IDEA, as they are generated by Git itself. Shelve : IntelliJ IDEA will put local changes to a shelf. Shelving is done by IntelliJ IDEA, and patches generated from shelved changes are normally applied inside IntelliJ IDEA. |
| Auto-update if push of the current branch was rejected | |
| Show Push dialog for Commit and Push | Select this option if you want the Push dialog to be displayed after you’ve clicked Commit and Push in the Commit Changes dialog. Otherwise, your changes will be pushed automatically to the affected repository. |
| Show Push dialog only when committing to protected branches | Select this option if you only want to show the Push Changes dialog if you are pushing to a protected branch when you’ve clicked Commit and Push in the Commit Changes dialog. Otherwise, your changes will be pushed automatically to the affected repository. |
| Protected branches |