Версия 2.9
Урок описывает использование EGit, плагин Eclipse для использования распределенной системы контроля версий Git. Это руководство основан на Eclipse 4.2 (Juno)
1. Что такое EGit
EGit является представителем Eclipse Team для распределенной системы контроля версий Git. EGit позволяет выполнять команды Git из Eclipse IDE.
EGit основан на библиотеке JGit. JGit - библиотека, которая реализует функциональность Git на Java.
2. Консольный Git
Это руководство описывает использование EGit. Если вам нужно выучить использование консольного Git, вы можете использовать Git Tutorial как справочник.
Большинство пакетов Eclipse 4.2 с Eclipse.org содержат EGit по умолчанию. В этом случае дополнительная установка не нужна.
Если EGit пропущен в вашей инсталляции Eclipse, вы можете установить его через Eclipse Update Manager через: Help → Install new Software. EGit может быть установлен по следующей URL: http://download.eclipse.org/egit/updates
Если EGit пропущен в вашей инсталляции Eclipse, вы можете установить его через Eclipse Update Manager через: Help → Install new Software. EGit может быть установлен по следующей URL: http://download.eclipse.org/egit/updates
Следующий раздел объясняет как создать репозиторий для одного проекта и повазывает как сделать "checkout" для существующего проекта из удаленного репозитория.
Create a new Java project called de.vogella.git.first in Eclipse. Create the
de.vogella.git.first
package and the following class.package de.vogella.git.first; public class GitTest { public static void main(String[] args) { System.out.println("Git is fun"); } }
Right click on your project, select
→ → . On the next dialog press the button.
EGit will propose an directory outside your workspace. Enter your project name as
Name
for your local Git repository. Select the button.
The wizard shows you the settings for your local Git repository. Select the
button to put your repository under Git version control.
You have created a local Git repository. The git repository is in this case directly stored in the specified folder in a
.git
folder. The following screenshot shows the directory structure based on the tree -a
command.
Create a
.gitignore
file in your project with the following content.bin .metadata
All files and directories which apply to the pattern described in this file will be ignored by Git. In this example all files in the
bin
and the .metadata
directory will be ignored.
The Git Staging View allows to stage changes and to commit them.
Open the Git Staging View via the menu → → → → .
Mark all files which have changed on drag them into the Staged Changes area.
Write a descriptive commmit message and press the
button which is hightlighted in the following screenshot.
Now the first version of your Java project is under version control.
Change the
System.out.println
message in your GitTest
class.package de.vogella.git.first; public class GitTest { public static void main(String[] args) { System.out.println("Git is cool"); } }
Drag the file which you have changed into the Staged Changes area, write a good commit message and press the commit button.
This change will now be in your local Git repository.
Open the Git repository view via the following menu entries:
→ → → → .
Select your project, right click on it and select
→ to see the timeline of changes.
If you select a commit you see the commit message and the involved files.
Via right mouse click on an individual file you can compare this file with its ancestor (the commit before that) or with the current version in the workspace.
The commit message describes the changes done by a commit and is used as the first point of checking the history of a Git repository.
A commit message should therefore be descriptive and informative without repeating the code changes.
A commit message should have a header and a body. The header should be less than 50 characters and the body should wrap its text at 72 so that the commit messages is displayed well on the command line. The body should be separated by the header with an empty line.
The body should contain the reason why the change was made.
The commit message should be in present tense, e.g. "Add better error handling" instead of "Added better error handling".
EGit has a Git repository view which allow you to browse your repositories, checkout projects and manage your branches.
EGit allows to clone an existing Git repository.
Select
→ → → .
Select URI in the next dialog.
Press clone and enter the URL to your Git repository. Git supports several protocols, e.g.
git://
and https://
. You only have to paste the URL to the first line of the dialog, the rest will be filled out automatically.
Please note that some proxy servers block the
git://
protocol. If you face issues, please try to use the https://
protocol.
For example the following URI can be used to clone the example projects of the Eclipse 4 application development book: git@github.com:vogella/eclipse4book.git
After pressing next the system will allow you to import the existing branches. You should select at least master as this is typically the main development branch.
The next dialog allows you to specify where the project should be copied to and which branch should be initially selected.
After the Git repository is cloned, EGit opens an additional import dialog which allows to import the Eclipse projects from the Git repository.
Once this dialog is completed, you have checked out (cloned) the projects into a local Git repository and you can use Git operation on these projects.
Once you have placed a project under version control you can start using team operations on your project. The team operations are available via right mouse click on your project. You can:
- Select→ , on the project node to add all files to version control.
- Select "Team" -> "Commit", to commit your changes to the local Git repository.
- Select "Team" -> "Push" to push your change to a remote Git repository (see the GitHub chapter).
- "Team" -> "Tag" allows you to create and manage tags.
EGit supports merging of branches to add the changes of one branch into another if this branch has not been changed. Select your project and
→ to start the merge dialog.
If you pull in changes or merge a branch and you have conflicting changes, EGit will highlight the affected files. EGit also supports the resolution of these merge conflicts.
Right click on a file with merge conflicts and select
→ .
This opens a dialog, asking you which merge mode you would like to use. The easiest way to see the conflicting changes is to use the Use HEAD (the last local version) of conflicting files as merge mode. This way you see the original changes on the left side and the conflicting changes on the right side.
You can manually edit the text on the left side or use the Copy current change from right to left button to copy the conflicting changes from right to left.
Once you have manually merged the changes, select
→ from the context menu of the resource to mark the conflicts as resolved and commit the merge resolution via → .
Git amend allows to adjust the last commit. For example you can change the commit message. The Git Staging view allows to perform the Git amend command via the the highlighted button in the following screenshot.
Git allows you to create branches, e.g. independent copies of the source code which can be changed independently from each other. The default branch is called master.
Git allows you to create branches very fast and cheaply in terms of resource consumption. Developers are encouraged to use branches frequently.
EGit allows to add annotations to see which line was changed by whom and which commit. To enable this, right click on your file and select
→ .
Afterwards you can place the mouse on the left side of the editor and a popup will show the commit information.
Git provides the
stash
command which allows to save the current uncommmitted changes and checkout the last committed revision.
This allows you to pull in the latest changes or to develop an urgent fix. Afterwards you can restore the stashed changes, which will reapply the changes to the current version of the source code.
In general using the stash command should be the exception in using Git. Typically you would create new branches for new features and switch between branches.
Eclipse allows to work with projects which are not included in the workspace.
To put several Eclipse projects into the same Git repository you can create a folder inside or outside your workspace and create the projects inside this folder. You can create a Git repository for this folder and all projects in this folder will be handled by the same repository. The best practice is to put the Git repository outsite of the Eclipse workspace.
You can import these projects into your workspace via
→ → →
To add a new Eclipse project to an existing Git repository, select the project, right click on it and select
→ → and select the existing Git repository.
EGit moves the projects to the repository and imports the project automatically into your workspace.
Create two Java projects called de.vogella.egit.multi.java1 and de.vogella.egit.multi.java2. Do not use the default location (which would be the workspace) but use a subfolder called
gitmulti
.
Create at least on Java class in each project. Git is not able to save empty folders.
Afterwards select both projects, right click on them and select
→ → .
You create a new Git repository which contains both projects.
Github is a popular hosting provider for Git projects and if you repository is public to everyone Github hosting is free. To use GitHub create an account on the Github Website. During the sign-up you will be asked to provide a "passphase". This "passphase" is later needed to push to Github from your local repository.
Create a new repository on Github, e.g. "de.vogella.git.github".
After creation of your new repository Github tells you what to do if you would inport via the command line. As we are going to use EGit we can ignore this information.
Create a new project "de.vogella.git.github" and put it under version control. Right-mouse click on your project and select "Team" -> "Push". A dialog pops up. Maintain the following data. Adjust the hightlighted line so that you are using your user and your project name.
git+ssh://git@github.com/vogella/de.vogella.git.github
Maintain your passphase which you maintained during the Github setup.
Select your branch (you should currently only have master if you followed my tutorial), press "Add all branches spec" and select next.
Нажмите finish.
If you now select your github Dashboard and then your project you should see the commited files.
Eclipse Mylyn is a productively tool for programmers. There is a GitHub connector for Mylyn available, please seehttp://wiki.eclipse.org/EGit/GitHub/UserGuide for details. .
EGit is self-hosted on git://egit.eclipse.org. You can clone the EGit code from the repository using EGit using the following URL git://egit.eclipse.org/jgit.git and git://egit.eclipse.org/egit.git.
You also need some libraries from Orbit. See Libraries from Orbit for getting these libraries.
17. Вопросы и обсуждение
Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.
http://www.vogella.com/articles/Eclipse/article.html EGit IDE Tutorial
http://wiki.eclipse.org/EGit/User_Guide EGit User Guide
http://wiki.eclipse.org/EGit/Contributor_Guide EGit contributor guide
vogella Training Android and Eclipse Training from the vogella team
Android Tutorial Introduction to Android Programming
GWT Tutorial Program in Java and compile to JavaScript and HTML
Eclipse RCP Tutorial Create native applications in Java
JUnit Tutorial Test your application
Git Tutorial Put everything you have under distributed version control system