Skip to content

Commit b56260a

Browse files
Merge pull request #242 from dropbox/skip-auth-for-local-commands
Skip auth for help, version, and completion commands
2 parents d35b0c1 + d42fc0b commit b56260a

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

cmd/root.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,16 @@ var (
5050

5151
var config dropbox.Config
5252

53+
func commandSkipsAuth(cmd *cobra.Command) bool {
54+
for c := cmd; c != nil; c = c.Parent() {
55+
switch c.Name() {
56+
case "__complete", "__completeNoDesc", "completion", "help", "version":
57+
return true
58+
}
59+
}
60+
return false
61+
}
62+
5363
func oauthCredentials(tokenType string) string {
5464
switch tokenType {
5565
case tokenPersonal:
@@ -133,6 +143,10 @@ func makeDropboxConfig(token string, verbose bool, asMember string, domain strin
133143
}
134144

135145
func initDbx(cmd *cobra.Command, args []string) (err error) {
146+
if commandSkipsAuth(cmd) {
147+
return nil
148+
}
149+
136150
verbose, _ := cmd.Flags().GetBool("verbose")
137151
asMember, _ := cmd.Flags().GetString("as-member")
138152
domain, _ := cmd.Flags().GetString("domain")

cmd/root_test.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,62 @@ func newAuthTestCommand() *cobra.Command {
3838
return cmd
3939
}
4040

41+
func TestInitDbxSkipsAuthForLocalCommands(t *testing.T) {
42+
t.Setenv(envAccessToken, "")
43+
t.Setenv(envAuthFile, filepath.Join(t.TempDir(), "missing-auth.json"))
44+
45+
tests := []struct {
46+
name string
47+
cmd *cobra.Command
48+
}{
49+
{
50+
name: "version",
51+
cmd: &cobra.Command{Use: "version"},
52+
},
53+
{
54+
name: "help",
55+
cmd: &cobra.Command{Use: "help"},
56+
},
57+
{
58+
name: "completion",
59+
cmd: func() *cobra.Command {
60+
root := &cobra.Command{Use: "dbxcli"}
61+
completion := &cobra.Command{Use: "completion"}
62+
bash := &cobra.Command{Use: "bash"}
63+
completion.AddCommand(bash)
64+
root.AddCommand(completion)
65+
return bash
66+
}(),
67+
},
68+
{
69+
name: "complete",
70+
cmd: &cobra.Command{Use: "__complete"},
71+
},
72+
{
73+
name: "complete-no-desc",
74+
cmd: &cobra.Command{Use: "__completeNoDesc"},
75+
},
76+
}
77+
78+
for _, tt := range tests {
79+
t.Run(tt.name, func(t *testing.T) {
80+
if err := initDbx(tt.cmd, nil); err != nil {
81+
t.Fatalf("expected auth to be skipped, got %v", err)
82+
}
83+
})
84+
}
85+
}
86+
87+
func TestInitDbxStillRequiresAuthForDropboxCommands(t *testing.T) {
88+
t.Setenv(envAccessToken, "")
89+
t.Setenv(envAuthFile, filepath.Join(t.TempDir(), "missing-auth.json"))
90+
91+
cmd := newAuthTestCommand()
92+
if err := initDbx(cmd, nil); err == nil {
93+
t.Fatal("expected Dropbox command to require auth")
94+
}
95+
}
96+
4197
func TestInitDbxUsesAccessTokenEnv(t *testing.T) {
4298
origConfig := config
4399
defer func() { config = origConfig }()

0 commit comments

Comments
 (0)