refactor: simplify some code by using `cmp.Or` (#2253)

Andrey Nering created

Change summary

internal/agent/agent.go                    |  5 +----
internal/agent/tools/glob.go               |  6 ++----
internal/agent/tools/grep.go               |  6 ++----
internal/agent/tools/list_mcp_resources.go |  9 ++-------
internal/config/load.go                    | 16 ++++------------
internal/ui/dialog/arguments.go            |  6 ++----
internal/ui/dialog/models.go               |  9 ++-------
internal/ui/model/ui.go                    | 11 +++--------
8 files changed, 18 insertions(+), 50 deletions(-)

Detailed changes

internal/agent/agent.go 🔗

@@ -849,10 +849,7 @@ func (a *sessionAgent) generateTitle(ctx context.Context, sessionID string, user
 	title = thinkTagRegex.ReplaceAllString(title, "")
 
 	title = strings.TrimSpace(title)
-	if title == "" {
-		slog.Debug("Empty title; using fallback")
-		title = defaultSessionName
-	}
+	title = cmp.Or(title, defaultSessionName)
 
 	// Calculate usage and cost.
 	var openrouterCost *float64

internal/agent/tools/glob.go 🔗

@@ -2,6 +2,7 @@ package tools
 
 import (
 	"bytes"
+	"cmp"
 	"context"
 	_ "embed"
 	"fmt"
@@ -39,10 +40,7 @@ func NewGlobTool(workingDir string) fantasy.AgentTool {
 				return fantasy.NewTextErrorResponse("pattern is required"), nil
 			}
 
-			searchPath := params.Path
-			if searchPath == "" {
-				searchPath = workingDir
-			}
+			searchPath := cmp.Or(params.Path, workingDir)
 
 			files, truncated, err := globFiles(ctx, params.Pattern, searchPath, 100)
 			if err != nil {

internal/agent/tools/grep.go 🔗

@@ -3,6 +3,7 @@ package tools
 import (
 	"bufio"
 	"bytes"
+	"cmp"
 	"context"
 	_ "embed"
 	"encoding/json"
@@ -115,10 +116,7 @@ func NewGrepTool(workingDir string, config config.ToolGrep) fantasy.AgentTool {
 				searchPattern = escapeRegexPattern(params.Pattern)
 			}
 
-			searchPath := params.Path
-			if searchPath == "" {
-				searchPath = workingDir
-			}
+			searchPath := cmp.Or(params.Path, workingDir)
 
 			searchCtx, cancel := context.WithTimeout(ctx, config.GetTimeout())
 			defer cancel()

internal/agent/tools/list_mcp_resources.go 🔗

@@ -1,6 +1,7 @@
 package tools
 
 import (
+	"cmp"
 	"context"
 	_ "embed"
 	"fmt"
@@ -74,13 +75,7 @@ func NewListMCPResourcesTool(cfg *config.Config, permissions permission.Service)
 				if resource == nil {
 					continue
 				}
-				title := resource.Title
-				if title == "" {
-					title = resource.Name
-				}
-				if title == "" {
-					title = resource.URI
-				}
+				title := cmp.Or(resource.Title, resource.Name, resource.URI)
 				line := fmt.Sprintf("- %s", title)
 				if resource.URI != "" {
 					line = fmt.Sprintf("%s (%s)", line, resource.URI)

internal/config/load.go 🔗

@@ -278,13 +278,9 @@ func (c *Config) configureProviders(env env.Env, resolver VariableResolver, know
 
 		// Make sure the provider ID is set
 		providerConfig.ID = id
-		if providerConfig.Name == "" {
-			providerConfig.Name = id // Use ID as name if not set
-		}
+		providerConfig.Name = cmp.Or(providerConfig.Name, id) // Use ID as name if not set
 		// default to OpenAI if not set
-		if providerConfig.Type == "" {
-			providerConfig.Type = catwalk.TypeOpenAICompat
-		}
+		providerConfig.Type = cmp.Or(providerConfig.Type, catwalk.TypeOpenAICompat)
 		if !slices.Contains(catwalk.KnownProviderTypes(), providerConfig.Type) && providerConfig.Type != hyper.Name {
 			slog.Warn("Skipping custom provider due to unsupported provider type", "provider", id)
 			c.Providers.Del(id)
@@ -412,9 +408,7 @@ func (c *Config) setDefaults(workingDir, dataDir string) {
 			c.Options.Attribution.TrailerStyle = TrailerStyleAssistedBy
 		}
 	}
-	if c.Options.InitializeAs == "" {
-		c.Options.InitializeAs = defaultInitializeAs
-	}
+	c.Options.InitializeAs = cmp.Or(c.Options.InitializeAs, defaultInitializeAs)
 }
 
 // applyLSPDefaults applies default values from powernap to LSP configurations
@@ -445,9 +439,7 @@ func (c *Config) applyLSPDefaults() {
 		if len(cfg.RootMarkers) == 0 {
 			cfg.RootMarkers = base.RootMarkers
 		}
-		if cfg.Command == "" {
-			cfg.Command = base.Command
-		}
+		cfg.Command = cmp.Or(cfg.Command, base.Command)
 		if len(cfg.Args) == 0 {
 			cfg.Args = base.Args
 		}

internal/ui/dialog/arguments.go 🔗

@@ -1,6 +1,7 @@
 package dialog
 
 import (
+	"cmp"
 	"strings"
 
 	"charm.land/bubbles/v2/help"
@@ -311,10 +312,7 @@ func (a *Arguments) Draw(scr uv.Screen, area uv.Rectangle) *tea.Cursor {
 	// Use standard header
 	titleStyle := s.Dialog.Title
 
-	titleText := a.title
-	if titleText == "" {
-		titleText = "Arguments"
-	}
+	titleText := cmp.Or(a.title, "Arguments")
 
 	header := common.DialogTitle(s, titleText, width, s.Primary, s.Secondary)
 

internal/ui/dialog/models.go 🔗

@@ -445,18 +445,13 @@ func (m *Models) setProviderItems() error {
 					}
 					continue
 				}
-				if model.Name == "" {
-					model.Name = model.ID
-				}
+				model.Name = cmp.Or(model.Name, model.ID)
 				displayProvider.Models = append(displayProvider.Models, model)
 				modelIndex[model.ID] = len(displayProvider.Models) - 1
 			}
 		}
 
-		name := displayProvider.Name
-		if name == "" {
-			name = providerID
-		}
+		name := cmp.Or(displayProvider.Name, providerID)
 
 		group := NewModelGroup(t, name, providerConfigured)
 		for _, model := range displayProvider.Models {

internal/ui/model/ui.go 🔗

@@ -2,6 +2,7 @@ package model
 
 import (
 	"bytes"
+	"cmp"
 	"context"
 	"errors"
 	"fmt"
@@ -1393,10 +1394,7 @@ func (m *UI) handleDialogMsg(msg tea.Msg) tea.Cmd {
 	case dialog.ActionRunMCPPrompt:
 		if len(msg.Arguments) > 0 && msg.Args == nil {
 			m.dialog.CloseFrontDialog()
-			title := msg.Title
-			if title == "" {
-				title = "MCP Prompt Arguments"
-			}
+			title := cmp.Or(msg.Title, "MCP Prompt Arguments")
 			argsDialog := dialog.NewArguments(
 				m.com,
 				title,
@@ -2563,10 +2561,7 @@ func (m *UI) insertFileCompletion(path string) tea.Cmd {
 // insertMCPResourceCompletion inserts the selected resource into the textarea,
 // replacing the @query, and adds the resource as an attachment.
 func (m *UI) insertMCPResourceCompletion(item completions.ResourceCompletionValue) tea.Cmd {
-	displayText := item.Title
-	if displayText == "" {
-		displayText = item.URI
-	}
+	displayText := cmp.Or(item.Title, item.URI)
 
 	if !m.insertCompletionText(displayText) {
 		return nil