4Trabes Historias de una empresa en 100 metros cuadrados

El blog de Trabe Soluciones

How to: automatically config a cloned repo

| | Comentarios

Important: If the version of Git you are running is under 1.7.7 this tip won’t run for you.

The problem

The other day I ran into a problem because of using the same computer for work and personal projects: I was commiting with the same user for both kind of projects, which I don’t want.

I want different user.email config setting for each type of project but I didn’t want to do it manually.

The solution

So I came up with a simple solution. It’s composed of four parts:

  • A particular, but not fancy, dir layout.
  • A config file per each type of repo (personal or work).
  • A bash function.
  • A git alias.

Using all this, as you’ll see, each time I clone a work or personal repo I end up with a different value of user.email depending on the type of project.

Dirs layout

Repos for personal and work projects must be contained into separated dirs so they have different config files. This is my layout:

1
2
3
4
5
6
7
8
[madtrick@madbook { repos } ruby-1.9.2-p180 ]
>>tree -L 1 -a personal/
personal/
├── .gitconfig.clone
├── cartos
├── coello
├── dotfiles
...
1
2
3
4
5
6
7
[madtrick@madbook { repos } ruby-1.9.2-p180 ]
>>tree -L 1 -a trabe/
trabe/
├── .gitconfig.clone
├── 4trabes
└── trabenet
...

Config file

The file .gitconfig.clone is where you place your specific bits of configuration. The syntax used is the same that you’ll use with git config

For example, the .gitconfig.clone for my work projects is this:

1
user.email=farruco.sanjurjo@trabesoluciones.com

Bash function

1
2
3
4
5
6
7
8
9
  function git_clone_config(){
    local options=""
    if [[ -f $PWD/.gitconfig.clone ]]; then
      while read line ; do
        options=$options" "$line
      done < $PWD/.gitconfig.clone
      echo "$options"
    fi
  }

When called, this function will look for a file called .gitconfig.clone in the current directory. If it exists, its lines will be returned (echoed).

Git alias

And to finish the git alias:

1
2
3
[alias]
  ...
  cl = !bash -ic 'git_clone_config' | xargs -I configvalues git clone --config configvalues --

Summary

When this alias is used, git cl REPO_URL, the bash function will be run to look for the .gitconfig.clone file. If that file exists its lines will be read and used in git clone --config CONFIG_LINES REPO_URL. This way, when git initializes the cloned repo it’ll use the config options given with --config flag.

Currently I’m using this just for the user.email config setting but it could be used to apply any of the supported config settings.

You can find my gitconfig file and other dot-stuff on my dotfiles repo on Github

Comments