Subject: Re: [PATCH 2/4] completion: introduce __git_find_subcommand

From: Junio C Hamano <[email-masked]>
Date: Fri, 26 Jan 2024 09:30:44 -0800

Rubén Justo <[email-masked]> writes:

> Let's have a function to get the current subcommand when completing
> commands that follow the syntax:
>
>     git <command> <subcommand>
>
> As a convenience, let's allow an optional "default subcommand" to be
> returned if none is found.
>
> Signed-off-by: Rubén Justo <[email-masked]>
> ---
>  contrib/completion/git-completion.bash | 20 ++++++++++++++++++++
>  1 file changed, 20 insertions(+)
>
> diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
> index 916e137021..5f2e904b56 100644
> --- a/contrib/completion/git-completion.bash
> +++ b/contrib/completion/git-completion.bash
> @@ -575,6 +575,26 @@ __gitcomp_subcommand ()
>  	fi
>  }
>  
> +# Find the current subcommand for commands that follow the syntax:
> +#
> +#    git <command> <subcommand>
> +#
> +# 1: List of possible subcommands.
> +# 2: Optional subcommand to return when none is found.
> +__git_find_subcommand ()
> +{
> +	local subcommand subcommands="$1" default_subcommand="$2"

Are the callers expected to form "$1" by concatenating known tokens
with a space?

I am just wondering if we can avoid looping, e.g.

	local nextword=${words[__git_cmd_idx+1]}
	case " $subcommands " in
	*" $nextword "*)
		echo "$nextword"
		return
		;;
	esac

It hopefully should not be a huge deal either way, though. 

> +
> +	for subcommand in $subcommands; do
> +		if [ "$subcommand" = "${words[__git_cmd_idx+1]}" ]; then
> +			echo $subcommand
> +			return
> +		fi
> +	done
> +
> +	echo $default_subcommand
> +}
> +
>  # Execute 'git ls-files', unless the --committable option is specified, in
>  # which case it runs 'git diff-index' to find out the files that can be
>  # committed.  It return paths relative to the directory specified in the first