Git Separated Worktree

erda-estremera-sxNt9g77PE0-unsplash-scaled.jpg
Photo by Erda Estremera on Unsplash Git allows to have separate work tree and repo. This is handy in a number of situations e.g.
  • managing configuration files into your home directory
  • any situation where you don’t want anyone or anything mess up your .git directory

bare repositories

  • git allows to create bare repositories (i.e. directories including only the git files and no working directory) with the following command in an empty directory.
    git init --bare
    
  • any repository path which does not end with “/.git” is considered a bare repository.

cloning

using the following syntax it is possible to separate the working directory
git clone <repository> --separate-git-dir <git-dir> <work-dir>
looking into work directory we can find a plain text file named .git which contains the following

gitdir: <path/to/repo/dir>

setting up a git repository for an existing directory

if the directory exists already we can follow this procedure:
  1. create the git repository in a different place e.g.
    cd ~/my_git_repos/
    git init --bare new_repo
    
  2. add a .git file in the existing directory with the following text

    gitdir: ~/my_git_repos/new_repo

  3. create a .gitignore file including all files and subdirectories we don’t want to include
  4. add the rest of the files to the index

HOME directory

one specific use case is configuration files in the home directory: this solution comes with a couple of warnings:
  • you may risk to add personal files to a repo, or files not intended to be saved
  • all subdirectories are seen as part of the repository
The solution can be done with these tips:
  1. move the .git file or rename it when you are not using the repository
  2. leave no bare files in your home directory; always use at least one subdirectory, so you can add it to gitignore

marco.p.v.vezzoli

Self taught assembler programming at 11 on my C64 (1983). Never stopped since then -- always looking up for curious things in the software development, data science and AI. Linux and FOSS user since 1994. MSc in physics in 1996. Working in large semiconductor companies since 1997 (STM, Micron) developing analytics and full stack web infrastructures, microservices, ML solutions

You may also like...