简体   繁体   中英

How can I set up the working directory and the local repository on different drives?

In Git, how can I set up the working directory and the local repository on different drives? The reason being to back up code on every local commit.

We employ a gatekeeper model on the 'master' repository, so I can't just push any old rubbish upstream, but I would like to ensure that any old rubbish is backed up every time I make a local commit.

Use git init 's --separate-git-dir flag

The git init command has a flag for that:

--separate-git-dir=<git dir>

Instead of initializing the repository as a directory to either $GIT_DIR or ./.git/ , create a text file there containing the path to the actual repository. This file acts as filesystem-agnostic Git symbolic link to the repository.

Example

For this example, let's assume that /Volumes/My_USB/ is the path to a USB drive. ( /Volumes is specific to Mac OS, but, other than this path, this example translates to other operating systems in a straightforward manner.)

To initialise a Git repository

  • whose working tree is the current directory,
  • whose "git directory" is /Volumes/My_USB/projectA_gitdir ,

simply run

git init --separate-git-dir="/Volumes/My_USB/projectA_gitdir"

To fix ideas,

  • inspect the contents of the .git file :

     $ cat .git gitdir: /Volumes/My_USB/projectA_gitdir 

    As you can see, it's just a text file containing the path to the git directory of your repo.

  • inspect the config of your local repo, by running

     $ git config --local --list 

    You should notice a line that isn't normally present when a repo has been initialised without the --separate-git-dir flag:

     core.worktree=<pwd> 

    where <pwd> is the path to the current directory.

  • inspect the contents of the git directory; if everything went well, a folder called projectA_gitdir must have been created on the USB drive and populated with everything that normally goes into the .git folder:

     $ ls /Volumes/My_USB/projectA_gitdir HEAD description info refs config hooks objects 

    All good :)

Of course, you will only be able to run Git commands on this repo if the drive is accessible. For instance, after unmounting it, here is what happens:

$ git status
fatal: Not a git repository: /Volumes/My_USB/projectA_gitdir

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM