Support tab completion for profiles (#572)

## Changes
Currently, `databricks --profile <TAB>` autocompletes with the shell
default behavior, listing files in the local directory. This is not a
great experience. Especially given that the suggested profile names for
accounts are so long, it can be cumbersome to type them out by hand.
This PR configures autocompletion for `--profile` to inspect the
profiles of ~/.databrickscfg.

One potential improvement is to filter the response based on whether the
command is known to be account-level or workspace-level.

## Tests
Manual test.
<img width="579" alt="Screenshot_11_07_2023__18_31"
src="https://github.com/databricks/cli/assets/1850319/d7a3acd0-2511-45ac-bd82-95567775c10a">
This commit is contained in:
Miles Yucht 2023-07-12 12:05:51 +02:00 committed by GitHub
parent 57e75d3e22
commit f203731fe6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 0 deletions

View File

@ -23,6 +23,7 @@ var currentUser int
func init() { func init() {
RootCmd.PersistentFlags().StringP("profile", "p", "", "~/.databrickscfg profile") RootCmd.PersistentFlags().StringP("profile", "p", "", "~/.databrickscfg profile")
RootCmd.RegisterFlagCompletionFunc("profile", databrickscfg.ProfileCompletion)
} }
func MustAccountClient(cmd *cobra.Command, args []string) error { func MustAccountClient(cmd *cobra.Command, args []string) error {

View File

@ -5,6 +5,7 @@ import (
"strings" "strings"
"github.com/databricks/databricks-sdk-go/config" "github.com/databricks/databricks-sdk-go/config"
"github.com/spf13/cobra"
) )
// Profile holds a subset of the keys in a databrickscfg profile. // Profile holds a subset of the keys in a databrickscfg profile.
@ -59,6 +60,10 @@ func MatchAccountProfiles(p Profile) bool {
return p.Host != "" && p.AccountID != "" return p.Host != "" && p.AccountID != ""
} }
func MatchAllProfiles(p Profile) bool {
return true
}
const DefaultPath = "~/.databrickscfg" const DefaultPath = "~/.databrickscfg"
func LoadProfiles(path string, fn ProfileMatchFunction) (file string, profiles Profiles, err error) { func LoadProfiles(path string, fn ProfileMatchFunction) (file string, profiles Profiles, err error) {
@ -99,3 +104,11 @@ func LoadProfiles(path string, fn ProfileMatchFunction) (file string, profiles P
return return
} }
func ProfileCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
_, profiles, err := LoadProfiles(DefaultPath, MatchAllProfiles)
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return profiles.Names(), cobra.ShellCompDirectiveNoFileComp
}