1

I'm working with mainly two types of repositories on my laptop, on one hand, the ones for my projects at work, and the other the ones for oss projects, but they use different user.email in git config --list (same user.name tho).

I'm wondering if there is a way to properly set the user.email (the one local to the repository) right from the start when I'm cloning a new project, (knowing that the global config is set to my oss projects).

The reason is that every now and then I forget to manually set the local configuration of my work projects and end up pushing commits signed with the wrong user (ie. the oss one) and then I had to rebase the last N commits or so, which can be quite annoying.

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
Natalie Perret
  • 8,013
  • 12
  • 66
  • 129

1 Answers1

4

Git itself does not have a way to do precisely what you've asked for. There are two obvious approaches to getting the same result, though.

  • One uses a feature that was new in Git version 2.13, called includeIf. Here, you would use the location within your collection of repositories to determine how to configure items. For details, see Git includeIf for personal and work profiles doesn't work.

  • The other is to stop using git clone to make clones. Instead, write your own command, that consists of running git clone, then running git config. For referring to this here, I'll call it git clone-and-config though you would probably want a short name like git cc.

    This command can be a Git alias that uses the ! syntax to run multiple commands, or a script named git-clone-and-config that Git can find so that git clone-and-config runs your git-clone-and-config script. Of course if you are going to write your own script, you can just call it whatever you want, and invoke it without the git prefix. The only reason to use the git prefix is to make it feel like it's "part of Git", even though you wrote it yourself.

    For details about this alternative, see How to embed bash script directly inside a git alias.

One last note: git clone can set configuration values in the new clone, at git clone time. So you can simplify the last part to:

git clone -c 'user.email=A U Thor <thor@example.com>' <url>

which means you can make it a non-! style Git alias:

[alias]
    cloneasfred = git clone -c 'user.email=Fred Flintstone <fflint@bedrock.prehisory>'
    cloneasbarney = git clone -c 'user.email=Barney Rubble <brub@bedrock.prehistory>'

Be careful! git -c user.email=... clone does not do the right thing, while git clone -c user.email=... does. The position of the -c is crucial here.

torek
  • 448,244
  • 59
  • 642
  • 775