Search code examples
eclipsegitegit

Does the .git local repository have to be contained in the local working directory?


Specifically I'm using Eclipse and egit:

  • using the wizard to share a project with egit, it moved the working directory out of the eclipse workspace into the folder I had chosen to hold git depositories
  • the .git repository was contained in this folder

My questions are:

  • I read that the git repository should not be in the Eclipse workspace but why can't the working directory be in the Eclipse workspace?
  • Is it because the local repository have to be contained inside the git working directory?

I've found a few questions about moving the directory back, but I don't want to do that without knowing why it was moved in the first place (I don't want to create problems for later).


Solution

  • No, the .git directory does not have to be in your working directory. You can point a Git repository at another directory as its working directory using the --work-tree option:

    --work-tree=<path>

    Set the path to the working tree. It can be an absolute path or a path relative to the current working directory. This can also be controlled by setting the GIT_WORK_TREE environment variable and the core.worktree configuration variable (see core.worktree in git-config(1) for a more detailed discussion).

    Consider the following example:

    $ # Create a Git repository
    $ mkdir project
    $ cd project
    $ git init
    Initialized empty Git repository in /path/to/project/.git/
    $ ls -a
    . .. .git
    
    $ # Now, start working in another directory
    $ cd ..
    $ mkdir working-directory
    $ cd working-directory
    $ echo foo > foo.txt
    
    $ # And now, commit to the initially created repository
    $ cd ../project
    $ git --work-tree=../working-directory status
    $ git --work-tree=../working-directory add foo.txt
    $ git --work-tree=../working-directory commi
    

    It is very likely that Eclipse is using this option internally.