Intellij idea как настроить git

Настройка 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.

In this field, specify the path to the Git executable file. Type the path or click Browse and specify the path in the dialog that opens.

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.

This option only becomes available if you have a multirooted project, that is there are several Git repositories within a single project.

Select this option if you want branch operations (such as checkout , merge , and so on.) to be applied synchronously to all repositories within your project.

Enable this option if you are more used to the concept of staging changes for commit instead of using changelists where modified files are staged automatically.

Using the staging area allows you to easily commit changes to the same file separately (including overlapping changes), and see which changes are already staged without switching focus from the editor. For details, see Use the Git staging area to commit changes.

If you enable the staging area, all existing changelists will be deleted.

Select this option to enable smart handling of LF and CRLF line separators. IntelliJ IDEA will analyze your configuration, warn you if you are about to commit CRLF into the repository, and suggest changing the core.autocrlf setting to true or input depending on your operating system.

This setting is not applied to files where you have set any related Git attributes. In this case, IntelliJ IDEA assumes that you clearly understand what you are doing and excludes such files from analysis.

If this option is deselected, you will have to fix issues with line endings manually using the Difference Viewer dialog.

Select this checkbox if you want the current branch to be updated automatically if the push operation from the current branch to its tracked branch is rejected.

If this option is deselected, IntelliJ IDEA will display the Push Rejected dialog when pushing a branch is rejected because your local repository and the remote storage are not synchronized.

Note the following:

If you have never seen the Push Rejected dialog before and you are enabling the checkbox initially, IntelliJ IDEA will update the conflicting local branch silently by means of the merge operation.

If you have already encountered the Push Rejected dialog and selected the Remember the update method choice. option, IntelliJ IDEA saves your last choice rebase or merge and will apply it to update the conflicting local branch silently.

Accordingly, to change the «remembered» setting, clear the checkbox, access the Push Rejected dialog, select the Auto-update if push . rejected option, and invoke another update strategy.

If you want to disable the ability to force push changes for certain branches, list them here (this is a team-shared parameter that is stored in .idea/vcs.xml ).

You can list several branches separated by a semicolon, or supply branch patterns as the input is treated as a list of regular expressions.

Источник

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 for some reason you need to manually configure IntelliJ IDEA to use Git from WSL, go to the Version Control | Git page of the IDE settings Ctrl+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 (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.

From the main menu, select Git | Clone , or, if no project is currently opened, 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.

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 project , 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 an existing project sources.

Associate the entire project with a single Git repository

Open the project that you want to put under Git.

Choose Enable Version Control Integration from the VCS Operations Popup Alt+` or from the main VCS menu.

Choose Git as the version control system and click OK .

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.

Associate different directories within the project with different Git repositories

Open the project that you want to put under Git.

From the main menu, choose 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 Ctrl+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 Ctrl+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 Ctrl+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 Local Changes view and choose Rollback .

Git lets you list ignored file patterns in two kinds of configuration files:

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 a 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 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 Local Changes view or in 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 files of a certain 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 Local Changes view, click on the toolbar and select Show Ignored Files .

Check project status

IntelliJ IDEA allows you to check the status of your local working copy compared to the repository version of the project. It uses specific colors to let you see which files have been modified, which new files have been added to the VCS, and which files are not being tracked by Git.

Open the Local Changes view.

The Default changelist shows all files that have been modified since you last synchronized with the remote repository (highlighted in blue), and all new files that have been added to the VCS but have not been committed yet (highlighted in green).

The Unversioned Files changelist shows all files that have been added to your project, but that are not being tracked by Git.

Track changes to a file in the editor

You can also track changes to a file as you modify it in the editor. All changes are highlighted with change markers that appear in the gutter next to the modified lines, and show the type of changes introduced since you last synchronized with the repository. When you commit changes to the repository, change markers disappear.

The changes you introduce to the text are color-coded:

line added.

line changed.

line deleted.

You can customize the default colors for line statuses on the Editor | Color Scheme | VCS page of the IDE settings Ctrl+Alt+S .

To disable VCS markers in the gutter, deselect the Highlight modified lines in the gutter option on the Editor | General page of the IDE settings Ctrl+Alt+S .

You can manage changes using a toolbar that appears when you hover the mouse cursor over a change marker and then click it. The toolbar is displayed together with a frame showing the previous contents of the modified line:

You can roll back changes by clicking and explore the differences between the current and the repository version of the current line by clicking .

Instead of reverting the whole file, you can copy any part of the contents of this popup and paste it into the editor.

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 all of your 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 information on how to share project settings for different project formats, see 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 Ctrl+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 you are going to push changes to your own fork of the original project. Another common scenario is that you have cloned your own repository that is somebody else’s project fork, and you need to synchronize with the original project and fetch changes from it.

From the main menu, choose 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.

Источник

Читайте также:  Как настроить смс когда недоступен
Оцените статью
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