简体   繁体   中英

Using and checking for optional parameters in a git alias function

I'm trying to do some crazy git-fu with aliases. Specifically, I want a git alias to read the incoming parameters based on whether they're empty, handle the command differently; kind of like overloading a function. I've gotten some good ideas for creating functions from other questions like this one but dealing with the parameters in a smart way is still eluding me.

What I ended up doing is creating 3 functions for varying levels of specificity and calling them in a chain with default values. Here's a piece I have in my git config.

# get the current local branch
current = symbolic-ref -q --short HEAD


# Calls sync-branch-with-origin-master using the current branch for the first property and origin as the remote name.
# ex. `git sync master` will checkout master from origin, pull the latest, checkout your current branch and rebase it with master.
sync = "!f() { currentBranch=$(git current); git sync-branch-with-master $currentBranch $1; }; f"

# get latest version of branch 2 from origin and rebase branch 1 onto it.
sync-branch-with-master = "!f() { git sync-branch-with-origin-master $1 origin $2; }; f"

# get latest version of branch $3 from origin $2 and rebase branch $1 onto it.
sync-branch-with-origin-master = "!f() { git checkout $3; git pull $2 $3; git checkout $1; git rebase $3; }; f"

This works great! But what I'd really like is something that checks to see if $3 or $2 exist and handle those cases differently.

By the way, I'm using bash on a Mac.

You can write an entire script inside the shell function ( f() , in each alias). That quickly becomes quite unreadable/unmaintainable though. For complex things I create a shell script and invoke that from the alias.

#! /bin/sh
# git-foo.sh
... body of script goes here ...

and then:

git config alias.foo '!git-foo.sh'

or whatever.

In this particular case, though, I suspect what you have is overkill :-) You may just want to use git pull --rebase or git fetch followed by git rebase . (Not that these are quite the same as what you have, so maybe not; but remember that git pull is basically the same as get fetch followed by git merge .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM