1
1

More than 1 year has passed since last update.

git pushでsimpleでもcurrent

Last updated at Posted at 2019-02-25

push.default = current は楽だけど、ちゃんと tracking 設定したいなぁ。でも push.default = simple でいちいち -u つけるのは面倒だなぁ。」という人向けに zsh で -u 付きのコマンドを提案するようにする。

$ git push
git push -u origin feature/foo-bar is correct? [n,y,a,e]:

.gitconfig の alias で設定したいけど、 git のコマンドは存在するコマンドを上書きさせてくれないので zsh で変更する。

まず、 setopt correctcorrect_all で修正を提示する感じをシミュレーションする。 SPROMPT にフォーマットが入っているので、 read で聞いて 0 から 3 の数値を返す。

function ask_ynae {
	local prompt=${SPROMPT/\%r/$1}
	while true; do
		read -rsk \?"$prompt" ynae
		case $ynae in
		[Yy] ) return 0 ;;
		"" | [Nn] ) return 1 ;;
		[Aa] ) return 2 ;;
		[Ee] ) return 3 ;;
		esac
		echo -ne "\r"
	done
}

実際に git をラップする部分。 \git のようバックスラッシュを使うと、置き換え前のコマンドを使える。組み込みの print コマンドは -z で次の編集中のコマンドにできる。

function in_git() {
	[[ "$(git rev-parse --is-inside-work-tree 2> /dev/null)" = "true" ]]
}
function wrapped_git() {
	if [[ "$*" = "push" ]] && in_git && ! (\git rev-parse --abbrev-ref @{upstream} >/dev/null 2>&1); then
		suggest="push -u origin $(\git rev-parse --abbrev-ref HEAD)"
		ask_ynae "git $suggest"
		exit_code=$?
		echo
		case $exit_code in
		"0" ) \git ${=suggest} ;;
		"1" ) \git $@ ;;
		"2" ) return 130 ;;
		"3" ) print -z "git $@" ;;
		esac
	else
		\git $@
	fi
}
alias git=wrapped_git
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1