Skip to content

Commit f5f5d12

Browse files
committed
Be more elegant in handling that no speakers are configured.
1 parent f15c5be commit f5f5d12

File tree

1 file changed

+49
-3
lines changed

1 file changed

+49
-3
lines changed

cmd/kefw2/cmd/root.go

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,24 @@ func Execute() {
8282
ExecName: cc.Bold,
8383
Flags: cc.Bold,
8484
})
85+
86+
// Pre-run check to ensure we have a speaker configured except for config and version commands
87+
rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {
88+
// Skip check for these commands
89+
if commandRequiresAsSpeaker(cmd) {
90+
return
91+
}
92+
93+
if currentSpeaker == nil && len(speakers) == 0 {
94+
fmt.Fprintf(os.Stderr, "No speakers configured. Please configure a speaker first:\n")
95+
fmt.Fprintf(os.Stderr, "- Discover speakers automatically:\n")
96+
fmt.Fprintf(os.Stderr, " kefw2 config speaker discover --save\n")
97+
fmt.Fprintf(os.Stderr, "- Manually add a speaker:\n")
98+
fmt.Fprintf(os.Stderr, " kefw2 config speaker add IP_ADDRESS\n")
99+
os.Exit(1)
100+
}
101+
}
102+
85103
err := rootCmd.Execute()
86104
if err != nil {
87105
os.Exit(1)
@@ -146,16 +164,44 @@ func initConfig() {
146164
break
147165
}
148166
}
167+
168+
// If no default speaker is set but we have a speaker, use the first one
169+
if defaultSpeaker == nil && len(speakers) == 1 {
170+
defaultSpeaker = &speakers[0]
171+
viper.Set("defaultSpeaker", defaultSpeaker.IPAddress)
172+
viper.WriteConfig()
173+
fmt.Printf("No default speaker was set. Using first available speaker as default: %s (%s)\n",
174+
defaultSpeaker.Name, defaultSpeaker.IPAddress)
175+
}
176+
149177
if currentSpeakerParam != "" {
150178
newSpeaker, err := kefw2.NewSpeaker(currentSpeakerParam)
151179
if err != nil {
152180
fmt.Printf("Hmm, %s does not look like it is a KEF W2 speaker:\n%s\n", currentSpeakerParam, err.Error())
153181
}
154182
currentSpeaker = &newSpeaker
155183
} else {
156-
if defaultSpeaker == nil {
157-
log.Println("Default speaker not found. Set it with `kefw2 config speaker default` or specify it with the --speaker (-s) flag")
158-
}
159184
currentSpeaker = defaultSpeaker
160185
}
161186
}
187+
188+
func commandRequiresAsSpeaker(cmd *cobra.Command) bool {
189+
if cmd.Name() == "config" {
190+
configSubCmd := cmd.Parent()
191+
if configSubCmd != nil {
192+
if configSubCmd.Name() == "config" {
193+
return false
194+
}
195+
configSubSubCmd := configSubCmd.Parent()
196+
if configSubSubCmd != nil {
197+
if configSubSubCmd.Name() == "config" {
198+
return false
199+
}
200+
}
201+
}
202+
}
203+
if cmd.Name() == "version" {
204+
return false
205+
}
206+
return true
207+
}

0 commit comments

Comments
 (0)