Using Git Locally

From IntelliJ-Wiki

Jump to: navigation, search

Contents

Introduction

IntelliJ IDEA supports integration with the Git version control system and provides interface for Git operations within the lifecycle of your project. This tutorial will walk you step by step through the first, locally performed, development cycle of a project under Git version control.

In this tutorial you will:

What This tutorial Is Not About

This tutorial does not teach you the ideology of Git. It shows how you can perform basic Git operations right from IntelliJ IDEA.

Prerequisites

  1. You are working with IntelliJ IDEA version 9 or higher.
  2. Git 1.6.0 or higher is installed on your computer.
  3. The Git integration plugin is enabled and the location of the Git executable file is correctly specified on the Git page of the Settings dialog box.
  4. You have an IntelliJ IDEA project with one plain Java module without any additional technologies enabled. The project name is not significant. This tutorial will be illustrated by a project with the name hello_world_java.
  5. You have access to the GitHub storage.

Setting Up a Local Git Repository

Technically, Git sets up a local repository by creating a .git folder in the specified parent directory. After that all the files in the directories below this parent can be considered stored in this repository. In our case, let’s create a .git directory right below the project root.

On the main menu, choose Version Control | Git Init.

Image 1.

In the Select directory for git init dialog box that opens, choose the project root folder hello_world_java as the location for the .git directory and click OK.

Image 2.

Putting the Project under Git Version Control

After you specify the location of the .git directory and click OK in the Select directory for git init dialog box, IntelliJ IDEA asks you whether you want to add the project root as Version Control root.

Image3.

Accept the suggestion by clicking Yes. Now, if you open the Version Control page of the Settings dialog box (see Image 4), you will see, that Git is specified as the version control system for the project root:

Image4.

However, if you open the Changes tool window (see Image 5), you will see a number of IntelliJ IDEA internal files in the list of unversioned files.

Image 5.

Let’s get rid of this list by telling the Git integration to ignore them. This is done on the Version Control - Ignored Files page of the Settings dialog box (see Image 6). The page shows a list of files that you do not need to put under version control. Particular files, entire directories, and mask definitions are acceptable.

Image 6.

We now need to expand the list with the project definition file .iml and all the files below the .idea folder. To do that, click Add. IntelliJ IDEA opens the Ignore Unversioned Files dialog box (Image 7).

Select the Ignore specified file option (1), click the Browse button File:browseButton.png(3), and select the C://Git/hello_world_java.iml file in the Select File to Ignore dialog box that opens. Alternatively, select the Ignore all files matching option (4) and type the *.iml mask in the text box. In either case, when you click OK, IntelliJ IDEA brings you back to the Ignore Unversioned Files dialog box, where the specified file or mask is added to the list.

To have all files in the .idea folder ignored, click the Add button again. In the Ignore Unversioned Files dialog box, select the Ignore all files under option (2), click the Browse button File:browseButton.png(3), and select the .idea folder in the Select File to Ignore dialog box that opens.

Image 7.

When you click OK, you return to the Ignore Unversioned Files dialog box where the list of ignored files looks as follows (Image 8):

Image 8.

Click OK. Now, if you open the Changes tool window, you will see that the Unversioned files list is not displayed.

Developing the Basic Functionality in the Master Branch

Now let’s develop the “obligatory” Hello world application in the master branch, which is yet the single branch in our repository. Create a HelloWorld (Image 9): right-click the src directory (1) in the Project tool window, point to New on the context menu, and choose Java Class.

Image 9.

In the New Class dialog box (Image 10), type HelloWorld (1) in the Name text box and click OK.

Image 10.

IntelliJ IDEA asks you to confirm putting the new file under Git version control:

Image 11.

Confirm the suggestion by clicking Yes. After that IntelliJ IDEA creates the stub file for you and opens it in the editor tab:

Image 12.

Add the following code to the stub:

     public static void main(String[] args) {
        System.out.print("Hello world!");
    }

Running the Application

Now, let’s run our application to make sure that it works, before committing the updates to the local repository. To do that, we need a run configuration. Fortunately, IntelliJ IDEA has already created the default configuration hello_world_java for us. Just press Ctrl+Shift+F10 and IntelliJ IDEA opens the Run tool window (Image 12) that shows the application output. Predictably, it is the string Hello world!:

Image 12.

Congratulations! Our application works, so we can commit the updates to the local repository.

Committing Changes to Master (Revision 1)

IntelliJ IDEA has a dedicated Changes tool window with the Local tab listing all the Git-controlled files that have been changed since the last commit.

Let’s look at this tool window (Image 13). The modified files are grouped in the Default changelist (1). You can create other changelists and move files among them, however one Default changelist is enough by now. In our case, the Default changelist contains one file HelloWorld.java. To commit the changes made in it to our local repository, right-click the Default changelist and select Commit Changes (2) on the context menu or just click the Commit Changes button File:icon_Commit.gif (3).

Image 13.

IntelliJ IDEA opens the Commit Changes dialog box (Image 14). Make sure that the check box next to the HelloWorld.java file (1) is selected, which means that the HelloWorld.java file is marked to be included in the commit.

Image 14.

In the Comment text box (2), provide a brief description, for example:

     Revision 1 – the Hello world functionality implemented.

Click Commit. The changes are saved to the master branch.

Expanding the Application Functionality in a New Branch

Now let’s slightly modify our application, so it asks the users to tell their names and then greet them in person. But to make sure that these improvements do not cause regression in the already existing functionality, let’s make the changes in another branch, which we will create for this purpose.

Creating a New Branch

Originally, the new branch will be a copy of master. We will save changes in this new branch and merge them into master, when we are sure that the entire application works.

To create a new branch, choose Version Control | Git | Checkout Branch.

Image 15.

IntelliJ IDEA opens the Checkout dialog box (Image 16) for creating a new branch.

The Git Root field (1) shows the project root C:\Git\hello_world_java. From the Checkout drop-down list (2), select the branch to copy the source from, in our case it is master. In the As new branch text box (3), type the name of the new branch, let’s name it personal_greeting_branch to reflect the changes in the functionality that we are going to implement in it. Make sure that the Track branch check box (4) is selected. This will let you always detect the parent of the current branch.

Image 16.

When you click Checkout, IntelliJ IDEA creates a copy of the master branch with the name personal_greeting_branch and automatically switches to it. Now the changes you make to the project sources will not affect the main, master, branch, until you merge them into it.

Let’s make sure that we are going to work in the right branch. Choose Version Control | Git | Current Branch on the main menu:

Image 17.

From the Current Branch dialog box that opens (Image 18) you will learn that we are in the personal_greeting_branch (1) that is the child of master (2):

Image 18.

Updating the Source Code

Open the HelloWorld.java file and update the main() method as follows:

  1. Remove the line System.out.print("Hello world!");
  2. Add the following code:
      public static void main(String[] argv) throws IOException {
        BufferedReader buff = new BufferedReader(
            new InputStreamReader(System.in));
        System.out.print("What's your name? ");
        System.out.flush();
        String s = buff.readLine();
        System.out.printf("Hello, %s!", s);
    }

IntelliJ IDEA detects several unresolved references and suggests quick fixes (Alt+Enter) for them. Accept all the import suggestions – IntelliJ IDEA will generate the following import statements:

      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;

Now our code looks as shown on Image 19. IntelliJ IDEA indicates changes as follows:

  • Newly added lines (1) are marked green in the gutter area.
  • Updated lines (2) are marked blue.
  • Unchanged lines (3) have no color indication.
  • The name of the file (4) in the header of the editor tab is displayed blue, which means that the file has been modified.
Image 19.

Checking the Functionality

Now, let’s run our application to check that it still works. We will re-use the HelloWorld configuration that IntelliJ IDEA created for us. Make sure that it is selected in the Run Configurations drop-down list and сlick File:runBuild.gif on the toolbar (Image 20).

Image 20.

IntelliJ IDEA opens the Run tool window (Image 21):

Image 21.

Introduce yourself, for example, type Jerry (Image 22):

Image 22.

IntelliJ IDEA displays the greeting (Image 23:

Image 23.

Committing Changes to Branch (Revision 2)

Now that we know that the new version of our program works, let’s commit the updates to the current branch personal_greeting_branch. We will make the same steps as when we were committing changes to the master branch: open the Changes tool window, right-click the Default changelist, and select Commit Changes on the context menu.

In the Commit Changes dialog box that opens, make sure that the check box next to the HelloWorld.java file is selected and type Revision 2 – the Personal Greeting functionality implemented in the Comment text box. When you click Commit, IntelliJ IDEA saves the changes to the personal_greeting_branch.

Troubleshooting: Resetting the HEAD Revision

Now let’s take a look at the issues that may arise. Suppose, you notice a small error in a recent commit and want to redo that part without showing the undo in the history. You need Git to consider an earlier commit as the latest commit in the current branch (HEAD). IntelliJ IDEA will help you with this operation also known as reset.

To illustrate this useful possibility, let’s reformat the code, commit the changes, and then reset the HEAD to the previous revision. Remember, that we are still in personal_greeting_branch.

To reformat the code, open the HelloWorld.java file, select the entire code, and choose Ctrl+Alt+L. IntelliJ IDEA will reformat the code according to the style settings. Commit the changes as in the previous cases, type Revision 3 – Code reformatted in the Comment text box.

Now let’s revert the committed reformatting. Choose Version Control | Git | Reset Head on the main menu to open the Reset Head dialog box (Image 24).

First of all, you can see that IntelliJ IDEA informs you that you are working with the right branch personal_greeting_branch (1). Make sure that the default method Mixed is selected in the Reset Type drop-down list (4).

Now, let’s specify the commit to reset the HEAD to. The required format is <branch name>~<number of commits backwards between the current HEAD and the required commit>. We want to discard one commit, the last one. So type personal_greeting_branch~1 in the To Commit text box (2).

Image 24.

Click Validate (3) to view the specified target commit in the Paths affected in commit... dialog box (Image 25) that opens.

Image 25

What we need here is the Comment field (1). The field shows the comment provided for Revision 2, when we implemented the Personal Greeting functionality. This means that we have specified the right commit. Click Closeto return to the Reset Head dialog box (Image 24).

Now you can safely click Reset. The last commit (Revision 3 in our example) is discarded and the previous commit becomes the HEAD of the branch.

However IntelliJ IDEA does not completely abandon the changes from the discarded commit. The IDE preserves the updates in HelloWorld.java and adds the file to the Default changelist (1) in the Changes tool window (Image 26).

Image 26.

We decided not to merge these updates to the master branch now. However we may need them later. So let’s put these updates aside in the form of a stash that can be applied at any time.

To do that, in the Changes tool window (Image 27), right-click the HelloWorld.java file (1) under the Default changelist. Then point at Git (2) and select Stash Changes (3) on the context menu.

Image 27.

In the Stash dialog box (Image 28), describe the contents of the stash in the Message test box (1), for example, type:

     Reformatting the code. The stash is created after HEAD reset. 
Image 28.

Then click the Create Stash button (2). The changes are stashed and can be applied at any time by activating the Version Control | Git | UnStash Changes command on the main menu.

Merging the personal_greeting_branch to master

At last we can introduce the updated application to the main branch, master. First of all, we need to switch to master: choose Version Control | Git | Checkout Branch' and select master from the Checkout drop-down list (1) in the Checkout dialog box (Image 29). Click Checkout (2) when ready.

Image 29.

To start the merge process itself, choose Version Control | Git | Merge Changes on the main menu:

Image 30.

IntelliJ IDEA displays the Merge Branches dialog box (Image 31), which shows that we are working with the master branch (1).

Now we need to specify the personal_greeting_branch as the branch to merge the changes from: in the Branch to merge list, select the check box next to the personal_greeting_branch (2).

Next, let’s choose the merge strategy. As you can see, the Default (3) value is preselected in the Strategy drop-down list. This means that Git will analyze the situation, detect the number of branches to be merged, and apply the strategy which it uses by default in such environment. For example, Git uses the Recursive strategy as default in our case when two branches are involved. Let’s rely on Git and accept the suggested Default (3) value.

Select the No commit check box (4). This will allow us view the merge results before committing them to master.

Image 31.

Click Merge when ready. The merge should pass automatically without any conflicts because we did not update the code in master. When you are through with merging, commit the changes.

This is all with the basics of using Git branches locally. The next section will give you some hints in uploading your work to a remote storage.

Uploading the Master Branch to a Remote Repository

One day, you may want to publish the results of your work. If you are going to use Git only locally, skip this section.

To publish your source code, you need write access to a remote storage, for example, to the GitHub storage. So first create an account and a remote repository following the storage-specific instructions.

To initiate publishing, open the hello_world_java project if it is closed and choose Version Control | Git | Push Changes on the main menu:

Choose Version Control | Git | Push Changes on the main menu:

Image 32.

IntelliJ IDEA displays the Push Changes dialog box (Image 33).

First, specify the target remote repository. In the Remote field (2), type the URL address of your storage in the format: <transport protocol><storage host><path to the remote repository>. Note, that the URL address git@github.com:zaikina/hello_world_java.git that the image displays is given as an example and will not work.

Second, we need to specify the branch to upload. From the Push drop-down list (2), choose Selected branches and select the check box next to the master branch in the Branches list(3).

Image 33.

Click Push when ready.

Useful Links

http://www.kernel.org/pub/software/scm/git/docs/user-manual.html

Personal tools