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

后端 未结 1 482
一整个雨季
一整个雨季 2021-01-24 23:10

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 gatekeep

相关标签:
1条回答
  • 2021-01-24 23:44

    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
    
    0 讨论(0)
提交回复
热议问题