diff --git a/cmd/root.go b/cmd/root.go index b103ad2..704b6a1 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -50,6 +50,16 @@ var ( var config dropbox.Config +func commandSkipsAuth(cmd *cobra.Command) bool { + for c := cmd; c != nil; c = c.Parent() { + switch c.Name() { + case "__complete", "__completeNoDesc", "completion", "help", "version": + return true + } + } + return false +} + func oauthCredentials(tokenType string) string { switch tokenType { case tokenPersonal: @@ -133,6 +143,10 @@ func makeDropboxConfig(token string, verbose bool, asMember string, domain strin } func initDbx(cmd *cobra.Command, args []string) (err error) { + if commandSkipsAuth(cmd) { + return nil + } + verbose, _ := cmd.Flags().GetBool("verbose") asMember, _ := cmd.Flags().GetString("as-member") domain, _ := cmd.Flags().GetString("domain") diff --git a/cmd/root_test.go b/cmd/root_test.go index 05b025b..ac9d799 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -38,6 +38,62 @@ func newAuthTestCommand() *cobra.Command { return cmd } +func TestInitDbxSkipsAuthForLocalCommands(t *testing.T) { + t.Setenv(envAccessToken, "") + t.Setenv(envAuthFile, filepath.Join(t.TempDir(), "missing-auth.json")) + + tests := []struct { + name string + cmd *cobra.Command + }{ + { + name: "version", + cmd: &cobra.Command{Use: "version"}, + }, + { + name: "help", + cmd: &cobra.Command{Use: "help"}, + }, + { + name: "completion", + cmd: func() *cobra.Command { + root := &cobra.Command{Use: "dbxcli"} + completion := &cobra.Command{Use: "completion"} + bash := &cobra.Command{Use: "bash"} + completion.AddCommand(bash) + root.AddCommand(completion) + return bash + }(), + }, + { + name: "complete", + cmd: &cobra.Command{Use: "__complete"}, + }, + { + name: "complete-no-desc", + cmd: &cobra.Command{Use: "__completeNoDesc"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := initDbx(tt.cmd, nil); err != nil { + t.Fatalf("expected auth to be skipped, got %v", err) + } + }) + } +} + +func TestInitDbxStillRequiresAuthForDropboxCommands(t *testing.T) { + t.Setenv(envAccessToken, "") + t.Setenv(envAuthFile, filepath.Join(t.TempDir(), "missing-auth.json")) + + cmd := newAuthTestCommand() + if err := initDbx(cmd, nil); err == nil { + t.Fatal("expected Dropbox command to require auth") + } +} + func TestInitDbxUsesAccessTokenEnv(t *testing.T) { origConfig := config defer func() { config = origConfig }()