Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
git-wrapper to protect against accidental usage of a global
=head1 NAME
git-wrapper - avoid committing as you@invalid
alias git=git-wrapper
Use this instead of the real B<git>
to protect yourself against committing stuff
with the wrong identity.
This requires that you do not configure a global
C<> value at all.
Unless your user name and host name
happen to be a really unlucky combination
which is equivalent to what you actually
want to use,
the default value will be unacceptable,
which this wrapper traps before it
chains to the real B<git>
for anything except F<git config>
(so you can set up your C<>
to what you want it to be in each
individual check-out)
and F<git clone>
(so you can clone :-)
and F<git init>.
alias git=git-wrapper
Add this to your F<.bash_profile> or similar to use globally.
=head1 HISTORY
I like to use different identities on different Git projects.
Inevitably, I ended up committing stuff with the wrong identity
more often than not (and needing to run the script I created
out of L<> all the time),
so I felt I had to come up with a fix. I played around with
Git aliases for a bit, but in the end, this turned out to be
the simplest and most usable solution.
=head1 AUTHOR
=head1 LICENSE
Creative Commons CC-SA
compare_emails () {
local global # sic
local local # sac
global=$(cd; git config
local=$(git config
case $global in $local)
echo "$0: '$global' is also local -- abort" >&2
return 55 ;;
return 0
case $1 in
config | clone | init | --help | -h ) ;;
*) compare_emails || exit $?;;
exec git "$@";

This comment has been minimized.

Copy link

@mitizhi mitizhi commented Aug 19, 2020

An alternative or perhaps complementary method to solve the email confusion is to automatically determine the user configuration to be used from the work directory path, using [includeIf "gitdir:...] section in your .gitconfig file.

For example, say you have git repositories for your employing company ACME and your future company DisruptiveUnicorns. Then in your ~/.gitignore you could have

[includeIf "gitdir:~/Work/ACME]
    path = ~/Work/ACME/.gitconfig
[includeIf "gitdir:~/Work/DisruptiveUnicorns]
   path = ~/Work/DisruptiveUnicorns/.gitconfig

Then you would create the two additional .gitconfig files with your desired contextual user (or other) configurations.

Then whatever you had in those files would be used to overwrite the configurations in your ~/.gitconfig based on whether your repository is somewhere under ~/Work/ACME/ or ~/Work/DisruptiveUnicorns (otherwise using the configurations in your ~/.gitconfig).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment