Add files using upload-large-folder tool
Browse files- projects/ui/crush/internal/cmd/root.go +187 -0
- projects/ui/crush/internal/cmd/run.go +58 -0
- projects/ui/crush/internal/cmd/schema.go +30 -0
- projects/ui/crush/internal/config/config.go +520 -0
- projects/ui/crush/internal/config/init.go +106 -0
- projects/ui/crush/internal/config/load.go +611 -0
- projects/ui/crush/internal/config/load_test.go +1186 -0
- projects/ui/crush/internal/config/merge.go +16 -0
- projects/ui/crush/internal/config/merge_test.go +27 -0
- projects/ui/crush/internal/config/provider.go +135 -0
- projects/ui/crush/internal/config/provider_empty_test.go +47 -0
- projects/ui/crush/internal/config/provider_test.go +73 -0
- projects/ui/crush/internal/config/resolve.go +176 -0
- projects/ui/crush/internal/config/resolve_test.go +332 -0
- projects/ui/crush/internal/csync/doc.go +3 -0
- projects/ui/crush/internal/csync/maps.go +129 -0
- projects/ui/crush/internal/csync/maps_test.go +687 -0
- projects/ui/crush/internal/csync/slices.go +145 -0
- projects/ui/crush/internal/csync/slices_test.go +271 -0
- projects/ui/crush/internal/db/connect.go +62 -0
projects/ui/crush/internal/cmd/root.go
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package cmd
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"fmt"
|
| 6 |
+
"io"
|
| 7 |
+
"log/slog"
|
| 8 |
+
"os"
|
| 9 |
+
"path/filepath"
|
| 10 |
+
|
| 11 |
+
tea "github.com/charmbracelet/bubbletea/v2"
|
| 12 |
+
"github.com/charmbracelet/crush/internal/app"
|
| 13 |
+
"github.com/charmbracelet/crush/internal/config"
|
| 14 |
+
"github.com/charmbracelet/crush/internal/db"
|
| 15 |
+
"github.com/charmbracelet/crush/internal/tui"
|
| 16 |
+
"github.com/charmbracelet/crush/internal/version"
|
| 17 |
+
"github.com/charmbracelet/fang"
|
| 18 |
+
"github.com/charmbracelet/x/term"
|
| 19 |
+
"github.com/spf13/cobra"
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
func init() {
|
| 23 |
+
rootCmd.PersistentFlags().StringP("cwd", "c", "", "Current working directory")
|
| 24 |
+
rootCmd.PersistentFlags().StringP("data-dir", "D", "", "Custom crush data directory")
|
| 25 |
+
rootCmd.PersistentFlags().BoolP("debug", "d", false, "Debug")
|
| 26 |
+
|
| 27 |
+
rootCmd.Flags().BoolP("help", "h", false, "Help")
|
| 28 |
+
rootCmd.Flags().BoolP("yolo", "y", false, "Automatically accept all permissions (dangerous mode)")
|
| 29 |
+
|
| 30 |
+
rootCmd.AddCommand(runCmd)
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
var rootCmd = &cobra.Command{
|
| 34 |
+
Use: "crush",
|
| 35 |
+
Short: "Terminal-based AI assistant for software development",
|
| 36 |
+
Long: `Crush is a powerful terminal-based AI assistant that helps with software development tasks.
|
| 37 |
+
It provides an interactive chat interface with AI capabilities, code analysis, and LSP integration
|
| 38 |
+
to assist developers in writing, debugging, and understanding code directly from the terminal.`,
|
| 39 |
+
Example: `
|
| 40 |
+
# Run in interactive mode
|
| 41 |
+
crush
|
| 42 |
+
|
| 43 |
+
# Run with debug logging
|
| 44 |
+
crush -d
|
| 45 |
+
|
| 46 |
+
# Run with debug logging in a specific directory
|
| 47 |
+
crush -d -c /path/to/project
|
| 48 |
+
|
| 49 |
+
# Run with custom data directory
|
| 50 |
+
crush -D /path/to/custom/.crush
|
| 51 |
+
|
| 52 |
+
# Print version
|
| 53 |
+
crush -v
|
| 54 |
+
|
| 55 |
+
# Run a single non-interactive prompt
|
| 56 |
+
crush run "Explain the use of context in Go"
|
| 57 |
+
|
| 58 |
+
# Run in dangerous mode (auto-accept all permissions)
|
| 59 |
+
crush -y
|
| 60 |
+
`,
|
| 61 |
+
RunE: func(cmd *cobra.Command, args []string) error {
|
| 62 |
+
app, err := setupApp(cmd)
|
| 63 |
+
if err != nil {
|
| 64 |
+
return err
|
| 65 |
+
}
|
| 66 |
+
defer app.Shutdown()
|
| 67 |
+
|
| 68 |
+
// Set up the TUI.
|
| 69 |
+
program := tea.NewProgram(
|
| 70 |
+
tui.New(app),
|
| 71 |
+
tea.WithAltScreen(),
|
| 72 |
+
tea.WithContext(cmd.Context()),
|
| 73 |
+
tea.WithMouseCellMotion(), // Use cell motion instead of all motion to reduce event flooding
|
| 74 |
+
tea.WithFilter(tui.MouseEventFilter), // Filter mouse events based on focus state
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
go app.Subscribe(program)
|
| 78 |
+
|
| 79 |
+
if _, err := program.Run(); err != nil {
|
| 80 |
+
slog.Error("TUI run error", "error", err)
|
| 81 |
+
return fmt.Errorf("TUI error: %v", err)
|
| 82 |
+
}
|
| 83 |
+
return nil
|
| 84 |
+
},
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
func Execute() {
|
| 88 |
+
if err := fang.Execute(
|
| 89 |
+
context.Background(),
|
| 90 |
+
rootCmd,
|
| 91 |
+
fang.WithVersion(version.Version),
|
| 92 |
+
fang.WithNotifySignal(os.Interrupt),
|
| 93 |
+
); err != nil {
|
| 94 |
+
os.Exit(1)
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
// setupApp handles the common setup logic for both interactive and non-interactive modes.
|
| 99 |
+
// It returns the app instance, config, cleanup function, and any error.
|
| 100 |
+
func setupApp(cmd *cobra.Command) (*app.App, error) {
|
| 101 |
+
debug, _ := cmd.Flags().GetBool("debug")
|
| 102 |
+
yolo, _ := cmd.Flags().GetBool("yolo")
|
| 103 |
+
dataDir, _ := cmd.Flags().GetString("data-dir")
|
| 104 |
+
ctx := cmd.Context()
|
| 105 |
+
|
| 106 |
+
cwd, err := ResolveCwd(cmd)
|
| 107 |
+
if err != nil {
|
| 108 |
+
return nil, err
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
cfg, err := config.Init(cwd, dataDir, debug)
|
| 112 |
+
if err != nil {
|
| 113 |
+
return nil, err
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
if cfg.Permissions == nil {
|
| 117 |
+
cfg.Permissions = &config.Permissions{}
|
| 118 |
+
}
|
| 119 |
+
cfg.Permissions.SkipRequests = yolo
|
| 120 |
+
|
| 121 |
+
if err := createDotCrushDir(cfg.Options.DataDirectory); err != nil {
|
| 122 |
+
return nil, err
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
// Connect to DB; this will also run migrations.
|
| 126 |
+
conn, err := db.Connect(ctx, cfg.Options.DataDirectory)
|
| 127 |
+
if err != nil {
|
| 128 |
+
return nil, err
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
appInstance, err := app.New(ctx, conn, cfg)
|
| 132 |
+
if err != nil {
|
| 133 |
+
slog.Error("Failed to create app instance", "error", err)
|
| 134 |
+
return nil, err
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
return appInstance, nil
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
func MaybePrependStdin(prompt string) (string, error) {
|
| 141 |
+
if term.IsTerminal(os.Stdin.Fd()) {
|
| 142 |
+
return prompt, nil
|
| 143 |
+
}
|
| 144 |
+
fi, err := os.Stdin.Stat()
|
| 145 |
+
if err != nil {
|
| 146 |
+
return prompt, err
|
| 147 |
+
}
|
| 148 |
+
if fi.Mode()&os.ModeNamedPipe == 0 {
|
| 149 |
+
return prompt, nil
|
| 150 |
+
}
|
| 151 |
+
bts, err := io.ReadAll(os.Stdin)
|
| 152 |
+
if err != nil {
|
| 153 |
+
return prompt, err
|
| 154 |
+
}
|
| 155 |
+
return string(bts) + "\n\n" + prompt, nil
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
func ResolveCwd(cmd *cobra.Command) (string, error) {
|
| 159 |
+
cwd, _ := cmd.Flags().GetString("cwd")
|
| 160 |
+
if cwd != "" {
|
| 161 |
+
err := os.Chdir(cwd)
|
| 162 |
+
if err != nil {
|
| 163 |
+
return "", fmt.Errorf("failed to change directory: %v", err)
|
| 164 |
+
}
|
| 165 |
+
return cwd, nil
|
| 166 |
+
}
|
| 167 |
+
cwd, err := os.Getwd()
|
| 168 |
+
if err != nil {
|
| 169 |
+
return "", fmt.Errorf("failed to get current working directory: %v", err)
|
| 170 |
+
}
|
| 171 |
+
return cwd, nil
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
func createDotCrushDir(dir string) error {
|
| 175 |
+
if err := os.MkdirAll(dir, 0o700); err != nil {
|
| 176 |
+
return fmt.Errorf("failed to create data directory: %q %w", dir, err)
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
gitIgnorePath := filepath.Join(dir, ".gitignore")
|
| 180 |
+
if _, err := os.Stat(gitIgnorePath); os.IsNotExist(err) {
|
| 181 |
+
if err := os.WriteFile(gitIgnorePath, []byte("*\n"), 0o644); err != nil {
|
| 182 |
+
return fmt.Errorf("failed to create .gitignore file: %q %w", gitIgnorePath, err)
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
return nil
|
| 187 |
+
}
|
projects/ui/crush/internal/cmd/run.go
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package cmd
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"log/slog"
|
| 6 |
+
"strings"
|
| 7 |
+
|
| 8 |
+
"github.com/spf13/cobra"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
var runCmd = &cobra.Command{
|
| 12 |
+
Use: "run [prompt...]",
|
| 13 |
+
Short: "Run a single non-interactive prompt",
|
| 14 |
+
Long: `Run a single prompt in non-interactive mode and exit.
|
| 15 |
+
The prompt can be provided as arguments or piped from stdin.`,
|
| 16 |
+
Example: `
|
| 17 |
+
# Run a simple prompt
|
| 18 |
+
crush run Explain the use of context in Go
|
| 19 |
+
|
| 20 |
+
# Pipe input from stdin
|
| 21 |
+
echo "What is this code doing?" | crush run
|
| 22 |
+
|
| 23 |
+
# Run with quiet mode (no spinner)
|
| 24 |
+
crush run -q "Generate a README for this project"
|
| 25 |
+
`,
|
| 26 |
+
RunE: func(cmd *cobra.Command, args []string) error {
|
| 27 |
+
quiet, _ := cmd.Flags().GetBool("quiet")
|
| 28 |
+
|
| 29 |
+
app, err := setupApp(cmd)
|
| 30 |
+
if err != nil {
|
| 31 |
+
return err
|
| 32 |
+
}
|
| 33 |
+
defer app.Shutdown()
|
| 34 |
+
|
| 35 |
+
if !app.Config().IsConfigured() {
|
| 36 |
+
return fmt.Errorf("no providers configured - please run 'crush' to set up a provider interactively")
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
prompt := strings.Join(args, " ")
|
| 40 |
+
|
| 41 |
+
prompt, err = MaybePrependStdin(prompt)
|
| 42 |
+
if err != nil {
|
| 43 |
+
slog.Error("Failed to read from stdin", "error", err)
|
| 44 |
+
return err
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
if prompt == "" {
|
| 48 |
+
return fmt.Errorf("no prompt provided")
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
// Run non-interactive flow using the App method
|
| 52 |
+
return app.RunNonInteractive(cmd.Context(), prompt, quiet)
|
| 53 |
+
},
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func init() {
|
| 57 |
+
runCmd.Flags().BoolP("quiet", "q", false, "Hide spinner")
|
| 58 |
+
}
|
projects/ui/crush/internal/cmd/schema.go
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package cmd
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"fmt"
|
| 6 |
+
|
| 7 |
+
"github.com/charmbracelet/crush/internal/config"
|
| 8 |
+
"github.com/invopop/jsonschema"
|
| 9 |
+
"github.com/spf13/cobra"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
var schemaCmd = &cobra.Command{
|
| 13 |
+
Use: "schema",
|
| 14 |
+
Short: "Generate JSON schema for configuration",
|
| 15 |
+
Long: "Generate JSON schema for the crush configuration file",
|
| 16 |
+
Hidden: true,
|
| 17 |
+
RunE: func(cmd *cobra.Command, args []string) error {
|
| 18 |
+
reflector := new(jsonschema.Reflector)
|
| 19 |
+
bts, err := json.MarshalIndent(reflector.Reflect(&config.Config{}), "", " ")
|
| 20 |
+
if err != nil {
|
| 21 |
+
return fmt.Errorf("failed to marshal schema: %w", err)
|
| 22 |
+
}
|
| 23 |
+
fmt.Println(string(bts))
|
| 24 |
+
return nil
|
| 25 |
+
},
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func init() {
|
| 29 |
+
rootCmd.AddCommand(schemaCmd)
|
| 30 |
+
}
|
projects/ui/crush/internal/config/config.go
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"fmt"
|
| 6 |
+
"log/slog"
|
| 7 |
+
"net/http"
|
| 8 |
+
"net/url"
|
| 9 |
+
"os"
|
| 10 |
+
"slices"
|
| 11 |
+
"strings"
|
| 12 |
+
"time"
|
| 13 |
+
|
| 14 |
+
"github.com/charmbracelet/catwalk/pkg/catwalk"
|
| 15 |
+
"github.com/charmbracelet/crush/internal/csync"
|
| 16 |
+
"github.com/charmbracelet/crush/internal/env"
|
| 17 |
+
"github.com/tidwall/sjson"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
const (
|
| 21 |
+
appName = "crush"
|
| 22 |
+
defaultDataDirectory = ".crush"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
var defaultContextPaths = []string{
|
| 26 |
+
".github/copilot-instructions.md",
|
| 27 |
+
".cursorrules",
|
| 28 |
+
".cursor/rules/",
|
| 29 |
+
"CLAUDE.md",
|
| 30 |
+
"CLAUDE.local.md",
|
| 31 |
+
"GEMINI.md",
|
| 32 |
+
"gemini.md",
|
| 33 |
+
"crush.md",
|
| 34 |
+
"crush.local.md",
|
| 35 |
+
"Crush.md",
|
| 36 |
+
"Crush.local.md",
|
| 37 |
+
"CRUSH.md",
|
| 38 |
+
"CRUSH.local.md",
|
| 39 |
+
"AGENTS.md",
|
| 40 |
+
"agents.md",
|
| 41 |
+
"Agents.md",
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
type SelectedModelType string
|
| 45 |
+
|
| 46 |
+
const (
|
| 47 |
+
SelectedModelTypeLarge SelectedModelType = "large"
|
| 48 |
+
SelectedModelTypeSmall SelectedModelType = "small"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
type SelectedModel struct {
|
| 52 |
+
// The model id as used by the provider API.
|
| 53 |
+
// Required.
|
| 54 |
+
Model string `json:"model" jsonschema:"required,description=The model ID as used by the provider API,example=gpt-4o"`
|
| 55 |
+
// The model provider, same as the key/id used in the providers config.
|
| 56 |
+
// Required.
|
| 57 |
+
Provider string `json:"provider" jsonschema:"required,description=The model provider ID that matches a key in the providers config,example=openai"`
|
| 58 |
+
|
| 59 |
+
// Only used by models that use the openai provider and need this set.
|
| 60 |
+
ReasoningEffort string `json:"reasoning_effort,omitempty" jsonschema:"description=Reasoning effort level for OpenAI models that support it,enum=low,enum=medium,enum=high"`
|
| 61 |
+
|
| 62 |
+
// Overrides the default model configuration.
|
| 63 |
+
MaxTokens int64 `json:"max_tokens,omitempty" jsonschema:"description=Maximum number of tokens for model responses,minimum=1,maximum=200000,example=4096"`
|
| 64 |
+
|
| 65 |
+
// Used by anthropic models that can reason to indicate if the model should think.
|
| 66 |
+
Think bool `json:"think,omitempty" jsonschema:"description=Enable thinking mode for Anthropic models that support reasoning"`
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
type ProviderConfig struct {
|
| 70 |
+
// The provider's id.
|
| 71 |
+
ID string `json:"id,omitempty" jsonschema:"description=Unique identifier for the provider,example=openai"`
|
| 72 |
+
// The provider's name, used for display purposes.
|
| 73 |
+
Name string `json:"name,omitempty" jsonschema:"description=Human-readable name for the provider,example=OpenAI"`
|
| 74 |
+
// The provider's API endpoint.
|
| 75 |
+
BaseURL string `json:"base_url,omitempty" jsonschema:"description=Base URL for the provider's API,format=uri,example=https://api.openai.com/v1"`
|
| 76 |
+
// The provider type, e.g. "openai", "anthropic", etc. if empty it defaults to openai.
|
| 77 |
+
Type catwalk.Type `json:"type,omitempty" jsonschema:"description=Provider type that determines the API format,enum=openai,enum=anthropic,enum=gemini,enum=azure,enum=vertexai,default=openai"`
|
| 78 |
+
// The provider's API key.
|
| 79 |
+
APIKey string `json:"api_key,omitempty" jsonschema:"description=API key for authentication with the provider,example=$OPENAI_API_KEY"`
|
| 80 |
+
// Marks the provider as disabled.
|
| 81 |
+
Disable bool `json:"disable,omitempty" jsonschema:"description=Whether this provider is disabled,default=false"`
|
| 82 |
+
|
| 83 |
+
// Custom system prompt prefix.
|
| 84 |
+
SystemPromptPrefix string `json:"system_prompt_prefix,omitempty" jsonschema:"description=Custom prefix to add to system prompts for this provider"`
|
| 85 |
+
|
| 86 |
+
// Extra headers to send with each request to the provider.
|
| 87 |
+
ExtraHeaders map[string]string `json:"extra_headers,omitempty" jsonschema:"description=Additional HTTP headers to send with requests"`
|
| 88 |
+
// Extra body
|
| 89 |
+
ExtraBody map[string]any `json:"extra_body,omitempty" jsonschema:"description=Additional fields to include in request bodies"`
|
| 90 |
+
|
| 91 |
+
// Used to pass extra parameters to the provider.
|
| 92 |
+
ExtraParams map[string]string `json:"-"`
|
| 93 |
+
|
| 94 |
+
// The provider models
|
| 95 |
+
Models []catwalk.Model `json:"models,omitempty" jsonschema:"description=List of models available from this provider"`
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
type MCPType string
|
| 99 |
+
|
| 100 |
+
const (
|
| 101 |
+
MCPStdio MCPType = "stdio"
|
| 102 |
+
MCPSse MCPType = "sse"
|
| 103 |
+
MCPHttp MCPType = "http"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
type MCPConfig struct {
|
| 107 |
+
Command string `json:"command,omitempty" jsonschema:"description=Command to execute for stdio MCP servers,example=npx"`
|
| 108 |
+
Env map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set for the MCP server"`
|
| 109 |
+
Args []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the MCP server command"`
|
| 110 |
+
Type MCPType `json:"type" jsonschema:"required,description=Type of MCP connection,enum=stdio,enum=sse,enum=http,default=stdio"`
|
| 111 |
+
URL string `json:"url,omitempty" jsonschema:"description=URL for HTTP or SSE MCP servers,format=uri,example=http://localhost:3000/mcp"`
|
| 112 |
+
Disabled bool `json:"disabled,omitempty" jsonschema:"description=Whether this MCP server is disabled,default=false"`
|
| 113 |
+
Timeout int `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for MCP server connections,default=15,example=30,example=60,example=120"`
|
| 114 |
+
|
| 115 |
+
// TODO: maybe make it possible to get the value from the env
|
| 116 |
+
Headers map[string]string `json:"headers,omitempty" jsonschema:"description=HTTP headers for HTTP/SSE MCP servers"`
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
type LSPConfig struct {
|
| 120 |
+
Disabled bool `json:"enabled,omitempty" jsonschema:"description=Whether this LSP server is disabled,default=false"`
|
| 121 |
+
Command string `json:"command" jsonschema:"required,description=Command to execute for the LSP server,example=gopls"`
|
| 122 |
+
Args []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the LSP server command"`
|
| 123 |
+
Env map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set to the LSP server command"`
|
| 124 |
+
Options any `json:"options,omitempty" jsonschema:"description=LSP server-specific configuration options"`
|
| 125 |
+
FileTypes []string `json:"filetypes,omitempty" jsonschema:"description=File types this LSP server handles,example=go,example=mod,example=rs,example=c,example=js,example=ts"`
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
type TUIOptions struct {
|
| 129 |
+
CompactMode bool `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
|
| 130 |
+
DiffMode string `json:"diff_mode,omitempty" jsonschema:"description=Diff mode for the TUI interface,enum=unified,enum=split"`
|
| 131 |
+
// Here we can add themes later or any TUI related options
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
type Permissions struct {
|
| 135 |
+
AllowedTools []string `json:"allowed_tools,omitempty" jsonschema:"description=List of tools that don't require permission prompts,example=bash,example=view"` // Tools that don't require permission prompts
|
| 136 |
+
SkipRequests bool `json:"-"` // Automatically accept all permissions (YOLO mode)
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
type Options struct {
|
| 140 |
+
ContextPaths []string `json:"context_paths,omitempty" jsonschema:"description=Paths to files containing context information for the AI,example=.cursorrules,example=CRUSH.md"`
|
| 141 |
+
TUI *TUIOptions `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
|
| 142 |
+
Debug bool `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
|
| 143 |
+
DebugLSP bool `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
|
| 144 |
+
DisableAutoSummarize bool `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
|
| 145 |
+
DataDirectory string `json:"data_directory,omitempty" jsonschema:"description=Directory for storing application data (relative to working directory),default=.crush,example=.crush"` // Relative to the cwd
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
type MCPs map[string]MCPConfig
|
| 149 |
+
|
| 150 |
+
type MCP struct {
|
| 151 |
+
Name string `json:"name"`
|
| 152 |
+
MCP MCPConfig `json:"mcp"`
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
func (m MCPs) Sorted() []MCP {
|
| 156 |
+
sorted := make([]MCP, 0, len(m))
|
| 157 |
+
for k, v := range m {
|
| 158 |
+
sorted = append(sorted, MCP{
|
| 159 |
+
Name: k,
|
| 160 |
+
MCP: v,
|
| 161 |
+
})
|
| 162 |
+
}
|
| 163 |
+
slices.SortFunc(sorted, func(a, b MCP) int {
|
| 164 |
+
return strings.Compare(a.Name, b.Name)
|
| 165 |
+
})
|
| 166 |
+
return sorted
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
type LSPs map[string]LSPConfig
|
| 170 |
+
|
| 171 |
+
type LSP struct {
|
| 172 |
+
Name string `json:"name"`
|
| 173 |
+
LSP LSPConfig `json:"lsp"`
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
func (l LSPs) Sorted() []LSP {
|
| 177 |
+
sorted := make([]LSP, 0, len(l))
|
| 178 |
+
for k, v := range l {
|
| 179 |
+
sorted = append(sorted, LSP{
|
| 180 |
+
Name: k,
|
| 181 |
+
LSP: v,
|
| 182 |
+
})
|
| 183 |
+
}
|
| 184 |
+
slices.SortFunc(sorted, func(a, b LSP) int {
|
| 185 |
+
return strings.Compare(a.Name, b.Name)
|
| 186 |
+
})
|
| 187 |
+
return sorted
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
func (l LSPConfig) ResolvedEnv() []string {
|
| 191 |
+
return resolveEnvs(l.Env)
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
func (m MCPConfig) ResolvedEnv() []string {
|
| 195 |
+
return resolveEnvs(m.Env)
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
func (m MCPConfig) ResolvedHeaders() map[string]string {
|
| 199 |
+
resolver := NewShellVariableResolver(env.New())
|
| 200 |
+
for e, v := range m.Headers {
|
| 201 |
+
var err error
|
| 202 |
+
m.Headers[e], err = resolver.ResolveValue(v)
|
| 203 |
+
if err != nil {
|
| 204 |
+
slog.Error("error resolving header variable", "error", err, "variable", e, "value", v)
|
| 205 |
+
continue
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
return m.Headers
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
type Agent struct {
|
| 212 |
+
ID string `json:"id,omitempty"`
|
| 213 |
+
Name string `json:"name,omitempty"`
|
| 214 |
+
Description string `json:"description,omitempty"`
|
| 215 |
+
// This is the id of the system prompt used by the agent
|
| 216 |
+
Disabled bool `json:"disabled,omitempty"`
|
| 217 |
+
|
| 218 |
+
Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
|
| 219 |
+
|
| 220 |
+
// The available tools for the agent
|
| 221 |
+
// if this is nil, all tools are available
|
| 222 |
+
AllowedTools []string `json:"allowed_tools,omitempty"`
|
| 223 |
+
|
| 224 |
+
// this tells us which MCPs are available for this agent
|
| 225 |
+
// if this is empty all mcps are available
|
| 226 |
+
// the string array is the list of tools from the AllowedMCP the agent has available
|
| 227 |
+
// if the string array is nil, all tools from the AllowedMCP are available
|
| 228 |
+
AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
|
| 229 |
+
|
| 230 |
+
// The list of LSPs that this agent can use
|
| 231 |
+
// if this is nil, all LSPs are available
|
| 232 |
+
AllowedLSP []string `json:"allowed_lsp,omitempty"`
|
| 233 |
+
|
| 234 |
+
// Overrides the context paths for this agent
|
| 235 |
+
ContextPaths []string `json:"context_paths,omitempty"`
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
// Config holds the configuration for crush.
|
| 239 |
+
type Config struct {
|
| 240 |
+
Schema string `json:"$schema,omitempty"`
|
| 241 |
+
|
| 242 |
+
// We currently only support large/small as values here.
|
| 243 |
+
Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
|
| 244 |
+
|
| 245 |
+
// The providers that are configured
|
| 246 |
+
Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
|
| 247 |
+
|
| 248 |
+
MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
|
| 249 |
+
|
| 250 |
+
LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
|
| 251 |
+
|
| 252 |
+
Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
|
| 253 |
+
|
| 254 |
+
Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
|
| 255 |
+
|
| 256 |
+
// Internal
|
| 257 |
+
workingDir string `json:"-"`
|
| 258 |
+
// TODO: most likely remove this concept when I come back to it
|
| 259 |
+
Agents map[string]Agent `json:"-"`
|
| 260 |
+
// TODO: find a better way to do this this should probably not be part of the config
|
| 261 |
+
resolver VariableResolver
|
| 262 |
+
dataConfigDir string `json:"-"`
|
| 263 |
+
knownProviders []catwalk.Provider `json:"-"`
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
func (c *Config) WorkingDir() string {
|
| 267 |
+
return c.workingDir
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
func (c *Config) EnabledProviders() []ProviderConfig {
|
| 271 |
+
var enabled []ProviderConfig
|
| 272 |
+
for p := range c.Providers.Seq() {
|
| 273 |
+
if !p.Disable {
|
| 274 |
+
enabled = append(enabled, p)
|
| 275 |
+
}
|
| 276 |
+
}
|
| 277 |
+
return enabled
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
// IsConfigured return true if at least one provider is configured
|
| 281 |
+
func (c *Config) IsConfigured() bool {
|
| 282 |
+
return len(c.EnabledProviders()) > 0
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
func (c *Config) GetModel(provider, model string) *catwalk.Model {
|
| 286 |
+
if providerConfig, ok := c.Providers.Get(provider); ok {
|
| 287 |
+
for _, m := range providerConfig.Models {
|
| 288 |
+
if m.ID == model {
|
| 289 |
+
return &m
|
| 290 |
+
}
|
| 291 |
+
}
|
| 292 |
+
}
|
| 293 |
+
return nil
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
|
| 297 |
+
model, ok := c.Models[modelType]
|
| 298 |
+
if !ok {
|
| 299 |
+
return nil
|
| 300 |
+
}
|
| 301 |
+
if providerConfig, ok := c.Providers.Get(model.Provider); ok {
|
| 302 |
+
return &providerConfig
|
| 303 |
+
}
|
| 304 |
+
return nil
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
|
| 308 |
+
model, ok := c.Models[modelType]
|
| 309 |
+
if !ok {
|
| 310 |
+
return nil
|
| 311 |
+
}
|
| 312 |
+
return c.GetModel(model.Provider, model.Model)
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
func (c *Config) LargeModel() *catwalk.Model {
|
| 316 |
+
model, ok := c.Models[SelectedModelTypeLarge]
|
| 317 |
+
if !ok {
|
| 318 |
+
return nil
|
| 319 |
+
}
|
| 320 |
+
return c.GetModel(model.Provider, model.Model)
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
func (c *Config) SmallModel() *catwalk.Model {
|
| 324 |
+
model, ok := c.Models[SelectedModelTypeSmall]
|
| 325 |
+
if !ok {
|
| 326 |
+
return nil
|
| 327 |
+
}
|
| 328 |
+
return c.GetModel(model.Provider, model.Model)
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
func (c *Config) SetCompactMode(enabled bool) error {
|
| 332 |
+
if c.Options == nil {
|
| 333 |
+
c.Options = &Options{}
|
| 334 |
+
}
|
| 335 |
+
c.Options.TUI.CompactMode = enabled
|
| 336 |
+
return c.SetConfigField("options.tui.compact_mode", enabled)
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
func (c *Config) Resolve(key string) (string, error) {
|
| 340 |
+
if c.resolver == nil {
|
| 341 |
+
return "", fmt.Errorf("no variable resolver configured")
|
| 342 |
+
}
|
| 343 |
+
return c.resolver.ResolveValue(key)
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
|
| 347 |
+
c.Models[modelType] = model
|
| 348 |
+
if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
|
| 349 |
+
return fmt.Errorf("failed to update preferred model: %w", err)
|
| 350 |
+
}
|
| 351 |
+
return nil
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
func (c *Config) SetConfigField(key string, value any) error {
|
| 355 |
+
// read the data
|
| 356 |
+
data, err := os.ReadFile(c.dataConfigDir)
|
| 357 |
+
if err != nil {
|
| 358 |
+
if os.IsNotExist(err) {
|
| 359 |
+
data = []byte("{}")
|
| 360 |
+
} else {
|
| 361 |
+
return fmt.Errorf("failed to read config file: %w", err)
|
| 362 |
+
}
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
newValue, err := sjson.Set(string(data), key, value)
|
| 366 |
+
if err != nil {
|
| 367 |
+
return fmt.Errorf("failed to set config field %s: %w", key, err)
|
| 368 |
+
}
|
| 369 |
+
if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
|
| 370 |
+
return fmt.Errorf("failed to write config file: %w", err)
|
| 371 |
+
}
|
| 372 |
+
return nil
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
func (c *Config) SetProviderAPIKey(providerID, apiKey string) error {
|
| 376 |
+
// First save to the config file
|
| 377 |
+
err := c.SetConfigField("providers."+providerID+".api_key", apiKey)
|
| 378 |
+
if err != nil {
|
| 379 |
+
return fmt.Errorf("failed to save API key to config file: %w", err)
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
providerConfig, exists := c.Providers.Get(providerID)
|
| 383 |
+
if exists {
|
| 384 |
+
providerConfig.APIKey = apiKey
|
| 385 |
+
c.Providers.Set(providerID, providerConfig)
|
| 386 |
+
return nil
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
var foundProvider *catwalk.Provider
|
| 390 |
+
for _, p := range c.knownProviders {
|
| 391 |
+
if string(p.ID) == providerID {
|
| 392 |
+
foundProvider = &p
|
| 393 |
+
break
|
| 394 |
+
}
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
if foundProvider != nil {
|
| 398 |
+
// Create new provider config based on known provider
|
| 399 |
+
providerConfig = ProviderConfig{
|
| 400 |
+
ID: providerID,
|
| 401 |
+
Name: foundProvider.Name,
|
| 402 |
+
BaseURL: foundProvider.APIEndpoint,
|
| 403 |
+
Type: foundProvider.Type,
|
| 404 |
+
APIKey: apiKey,
|
| 405 |
+
Disable: false,
|
| 406 |
+
ExtraHeaders: make(map[string]string),
|
| 407 |
+
ExtraParams: make(map[string]string),
|
| 408 |
+
Models: foundProvider.Models,
|
| 409 |
+
}
|
| 410 |
+
} else {
|
| 411 |
+
return fmt.Errorf("provider with ID %s not found in known providers", providerID)
|
| 412 |
+
}
|
| 413 |
+
// Store the updated provider config
|
| 414 |
+
c.Providers.Set(providerID, providerConfig)
|
| 415 |
+
return nil
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
func (c *Config) SetupAgents() {
|
| 419 |
+
agents := map[string]Agent{
|
| 420 |
+
"coder": {
|
| 421 |
+
ID: "coder",
|
| 422 |
+
Name: "Coder",
|
| 423 |
+
Description: "An agent that helps with executing coding tasks.",
|
| 424 |
+
Model: SelectedModelTypeLarge,
|
| 425 |
+
ContextPaths: c.Options.ContextPaths,
|
| 426 |
+
// All tools allowed
|
| 427 |
+
},
|
| 428 |
+
"task": {
|
| 429 |
+
ID: "task",
|
| 430 |
+
Name: "Task",
|
| 431 |
+
Description: "An agent that helps with searching for context and finding implementation details.",
|
| 432 |
+
Model: SelectedModelTypeLarge,
|
| 433 |
+
ContextPaths: c.Options.ContextPaths,
|
| 434 |
+
AllowedTools: []string{
|
| 435 |
+
"glob",
|
| 436 |
+
"grep",
|
| 437 |
+
"ls",
|
| 438 |
+
"sourcegraph",
|
| 439 |
+
"view",
|
| 440 |
+
},
|
| 441 |
+
// NO MCPs or LSPs by default
|
| 442 |
+
AllowedMCP: map[string][]string{},
|
| 443 |
+
AllowedLSP: []string{},
|
| 444 |
+
},
|
| 445 |
+
}
|
| 446 |
+
c.Agents = agents
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
func (c *Config) Resolver() VariableResolver {
|
| 450 |
+
return c.resolver
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
|
| 454 |
+
testURL := ""
|
| 455 |
+
headers := make(map[string]string)
|
| 456 |
+
apiKey, _ := resolver.ResolveValue(c.APIKey)
|
| 457 |
+
switch c.Type {
|
| 458 |
+
case catwalk.TypeOpenAI:
|
| 459 |
+
baseURL, _ := resolver.ResolveValue(c.BaseURL)
|
| 460 |
+
if baseURL == "" {
|
| 461 |
+
baseURL = "https://api.openai.com/v1"
|
| 462 |
+
}
|
| 463 |
+
testURL = baseURL + "/models"
|
| 464 |
+
headers["Authorization"] = "Bearer " + apiKey
|
| 465 |
+
case catwalk.TypeAnthropic:
|
| 466 |
+
baseURL, _ := resolver.ResolveValue(c.BaseURL)
|
| 467 |
+
if baseURL == "" {
|
| 468 |
+
baseURL = "https://api.anthropic.com/v1"
|
| 469 |
+
}
|
| 470 |
+
testURL = baseURL + "/models"
|
| 471 |
+
headers["x-api-key"] = apiKey
|
| 472 |
+
headers["anthropic-version"] = "2023-06-01"
|
| 473 |
+
case catwalk.TypeGemini:
|
| 474 |
+
baseURL, _ := resolver.ResolveValue(c.BaseURL)
|
| 475 |
+
if baseURL == "" {
|
| 476 |
+
baseURL = "https://generativelanguage.googleapis.com"
|
| 477 |
+
}
|
| 478 |
+
testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
|
| 479 |
+
}
|
| 480 |
+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
| 481 |
+
defer cancel()
|
| 482 |
+
client := &http.Client{}
|
| 483 |
+
req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
|
| 484 |
+
if err != nil {
|
| 485 |
+
return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
|
| 486 |
+
}
|
| 487 |
+
for k, v := range headers {
|
| 488 |
+
req.Header.Set(k, v)
|
| 489 |
+
}
|
| 490 |
+
for k, v := range c.ExtraHeaders {
|
| 491 |
+
req.Header.Set(k, v)
|
| 492 |
+
}
|
| 493 |
+
b, err := client.Do(req)
|
| 494 |
+
if err != nil {
|
| 495 |
+
return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
|
| 496 |
+
}
|
| 497 |
+
if b.StatusCode != http.StatusOK {
|
| 498 |
+
return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
|
| 499 |
+
}
|
| 500 |
+
_ = b.Body.Close()
|
| 501 |
+
return nil
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
func resolveEnvs(envs map[string]string) []string {
|
| 505 |
+
resolver := NewShellVariableResolver(env.New())
|
| 506 |
+
for e, v := range envs {
|
| 507 |
+
var err error
|
| 508 |
+
envs[e], err = resolver.ResolveValue(v)
|
| 509 |
+
if err != nil {
|
| 510 |
+
slog.Error("error resolving environment variable", "error", err, "variable", e, "value", v)
|
| 511 |
+
continue
|
| 512 |
+
}
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
res := make([]string, 0, len(envs))
|
| 516 |
+
for k, v := range envs {
|
| 517 |
+
res = append(res, fmt.Sprintf("%s=%s", k, v))
|
| 518 |
+
}
|
| 519 |
+
return res
|
| 520 |
+
}
|
projects/ui/crush/internal/config/init.go
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"os"
|
| 6 |
+
"path/filepath"
|
| 7 |
+
"strings"
|
| 8 |
+
"sync/atomic"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
const (
|
| 12 |
+
InitFlagFilename = "init"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
type ProjectInitFlag struct {
|
| 16 |
+
Initialized bool `json:"initialized"`
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
// TODO: we need to remove the global config instance keeping it now just until everything is migrated
|
| 20 |
+
var instance atomic.Pointer[Config]
|
| 21 |
+
|
| 22 |
+
func Init(workingDir, dataDir string, debug bool) (*Config, error) {
|
| 23 |
+
cfg, err := Load(workingDir, dataDir, debug)
|
| 24 |
+
if err != nil {
|
| 25 |
+
return nil, err
|
| 26 |
+
}
|
| 27 |
+
instance.Store(cfg)
|
| 28 |
+
return instance.Load(), nil
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
func Get() *Config {
|
| 32 |
+
cfg := instance.Load()
|
| 33 |
+
return cfg
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
func ProjectNeedsInitialization() (bool, error) {
|
| 37 |
+
cfg := Get()
|
| 38 |
+
if cfg == nil {
|
| 39 |
+
return false, fmt.Errorf("config not loaded")
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
flagFilePath := filepath.Join(cfg.Options.DataDirectory, InitFlagFilename)
|
| 43 |
+
|
| 44 |
+
_, err := os.Stat(flagFilePath)
|
| 45 |
+
if err == nil {
|
| 46 |
+
return false, nil
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
if !os.IsNotExist(err) {
|
| 50 |
+
return false, fmt.Errorf("failed to check init flag file: %w", err)
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
crushExists, err := crushMdExists(cfg.WorkingDir())
|
| 54 |
+
if err != nil {
|
| 55 |
+
return false, fmt.Errorf("failed to check for CRUSH.md files: %w", err)
|
| 56 |
+
}
|
| 57 |
+
if crushExists {
|
| 58 |
+
return false, nil
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
return true, nil
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
func crushMdExists(dir string) (bool, error) {
|
| 65 |
+
entries, err := os.ReadDir(dir)
|
| 66 |
+
if err != nil {
|
| 67 |
+
return false, err
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
for _, entry := range entries {
|
| 71 |
+
if entry.IsDir() {
|
| 72 |
+
continue
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
name := strings.ToLower(entry.Name())
|
| 76 |
+
if name == "crush.md" {
|
| 77 |
+
return true, nil
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
return false, nil
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
func MarkProjectInitialized() error {
|
| 85 |
+
cfg := Get()
|
| 86 |
+
if cfg == nil {
|
| 87 |
+
return fmt.Errorf("config not loaded")
|
| 88 |
+
}
|
| 89 |
+
flagFilePath := filepath.Join(cfg.Options.DataDirectory, InitFlagFilename)
|
| 90 |
+
|
| 91 |
+
file, err := os.Create(flagFilePath)
|
| 92 |
+
if err != nil {
|
| 93 |
+
return fmt.Errorf("failed to create init flag file: %w", err)
|
| 94 |
+
}
|
| 95 |
+
defer file.Close()
|
| 96 |
+
|
| 97 |
+
return nil
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
func HasInitialDataConfig() bool {
|
| 101 |
+
cfgPath := GlobalConfigData()
|
| 102 |
+
if _, err := os.Stat(cfgPath); err != nil {
|
| 103 |
+
return false
|
| 104 |
+
}
|
| 105 |
+
return Get().IsConfigured()
|
| 106 |
+
}
|
projects/ui/crush/internal/config/load.go
ADDED
|
@@ -0,0 +1,611 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"fmt"
|
| 6 |
+
"io"
|
| 7 |
+
"log/slog"
|
| 8 |
+
"maps"
|
| 9 |
+
"os"
|
| 10 |
+
"path/filepath"
|
| 11 |
+
"runtime"
|
| 12 |
+
"slices"
|
| 13 |
+
"strings"
|
| 14 |
+
|
| 15 |
+
"github.com/charmbracelet/catwalk/pkg/catwalk"
|
| 16 |
+
"github.com/charmbracelet/crush/internal/csync"
|
| 17 |
+
"github.com/charmbracelet/crush/internal/env"
|
| 18 |
+
"github.com/charmbracelet/crush/internal/fsext"
|
| 19 |
+
"github.com/charmbracelet/crush/internal/home"
|
| 20 |
+
"github.com/charmbracelet/crush/internal/log"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
const defaultCatwalkURL = "https://catwalk.charm.sh"
|
| 24 |
+
|
| 25 |
+
// LoadReader config via io.Reader.
|
| 26 |
+
func LoadReader(fd io.Reader) (*Config, error) {
|
| 27 |
+
data, err := io.ReadAll(fd)
|
| 28 |
+
if err != nil {
|
| 29 |
+
return nil, err
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
var config Config
|
| 33 |
+
err = json.Unmarshal(data, &config)
|
| 34 |
+
if err != nil {
|
| 35 |
+
return nil, err
|
| 36 |
+
}
|
| 37 |
+
return &config, err
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
// Load loads the configuration from the default paths.
|
| 41 |
+
func Load(workingDir, dataDir string, debug bool) (*Config, error) {
|
| 42 |
+
// uses default config paths
|
| 43 |
+
configPaths := []string{
|
| 44 |
+
globalConfig(),
|
| 45 |
+
GlobalConfigData(),
|
| 46 |
+
filepath.Join(workingDir, fmt.Sprintf("%s.json", appName)),
|
| 47 |
+
filepath.Join(workingDir, fmt.Sprintf(".%s.json", appName)),
|
| 48 |
+
}
|
| 49 |
+
cfg, err := loadFromConfigPaths(configPaths)
|
| 50 |
+
if err != nil {
|
| 51 |
+
return nil, fmt.Errorf("failed to load config from paths %v: %w", configPaths, err)
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
cfg.dataConfigDir = GlobalConfigData()
|
| 55 |
+
|
| 56 |
+
cfg.setDefaults(workingDir, dataDir)
|
| 57 |
+
|
| 58 |
+
if debug {
|
| 59 |
+
cfg.Options.Debug = true
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
// Setup logs
|
| 63 |
+
log.Setup(
|
| 64 |
+
filepath.Join(cfg.Options.DataDirectory, "logs", fmt.Sprintf("%s.log", appName)),
|
| 65 |
+
cfg.Options.Debug,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
// Load known providers, this loads the config from catwalk
|
| 69 |
+
providers, err := Providers()
|
| 70 |
+
if err != nil || len(providers) == 0 {
|
| 71 |
+
return nil, fmt.Errorf("failed to load providers: %w", err)
|
| 72 |
+
}
|
| 73 |
+
cfg.knownProviders = providers
|
| 74 |
+
|
| 75 |
+
env := env.New()
|
| 76 |
+
// Configure providers
|
| 77 |
+
valueResolver := NewShellVariableResolver(env)
|
| 78 |
+
cfg.resolver = valueResolver
|
| 79 |
+
if err := cfg.configureProviders(env, valueResolver, providers); err != nil {
|
| 80 |
+
return nil, fmt.Errorf("failed to configure providers: %w", err)
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
if !cfg.IsConfigured() {
|
| 84 |
+
slog.Warn("No providers configured")
|
| 85 |
+
return cfg, nil
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
if err := cfg.configureSelectedModels(providers); err != nil {
|
| 89 |
+
return nil, fmt.Errorf("failed to configure selected models: %w", err)
|
| 90 |
+
}
|
| 91 |
+
cfg.SetupAgents()
|
| 92 |
+
return cfg, nil
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
func PushPopCrushEnv() func() {
|
| 96 |
+
found := []string{}
|
| 97 |
+
for _, ev := range os.Environ() {
|
| 98 |
+
if strings.HasPrefix(ev, "CRUSH_") {
|
| 99 |
+
pair := strings.SplitN(ev, "=", 2)
|
| 100 |
+
if len(pair) != 2 {
|
| 101 |
+
continue
|
| 102 |
+
}
|
| 103 |
+
found = append(found, strings.TrimPrefix(pair[0], "CRUSH_"))
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
backups := make(map[string]string)
|
| 107 |
+
for _, ev := range found {
|
| 108 |
+
backups[ev] = os.Getenv(ev)
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
for _, ev := range found {
|
| 112 |
+
os.Setenv(ev, os.Getenv("CRUSH_"+ev))
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
restore := func() {
|
| 116 |
+
for k, v := range backups {
|
| 117 |
+
os.Setenv(k, v)
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
return restore
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
func (c *Config) configureProviders(env env.Env, resolver VariableResolver, knownProviders []catwalk.Provider) error {
|
| 124 |
+
knownProviderNames := make(map[string]bool)
|
| 125 |
+
restore := PushPopCrushEnv()
|
| 126 |
+
defer restore()
|
| 127 |
+
for _, p := range knownProviders {
|
| 128 |
+
knownProviderNames[string(p.ID)] = true
|
| 129 |
+
config, configExists := c.Providers.Get(string(p.ID))
|
| 130 |
+
// if the user configured a known provider we need to allow it to override a couple of parameters
|
| 131 |
+
if configExists {
|
| 132 |
+
if config.Disable {
|
| 133 |
+
slog.Debug("Skipping provider due to disable flag", "provider", p.ID)
|
| 134 |
+
c.Providers.Del(string(p.ID))
|
| 135 |
+
continue
|
| 136 |
+
}
|
| 137 |
+
if config.BaseURL != "" {
|
| 138 |
+
p.APIEndpoint = config.BaseURL
|
| 139 |
+
}
|
| 140 |
+
if config.APIKey != "" {
|
| 141 |
+
p.APIKey = config.APIKey
|
| 142 |
+
}
|
| 143 |
+
if len(config.Models) > 0 {
|
| 144 |
+
models := []catwalk.Model{}
|
| 145 |
+
seen := make(map[string]bool)
|
| 146 |
+
|
| 147 |
+
for _, model := range config.Models {
|
| 148 |
+
if seen[model.ID] {
|
| 149 |
+
continue
|
| 150 |
+
}
|
| 151 |
+
seen[model.ID] = true
|
| 152 |
+
if model.Name == "" {
|
| 153 |
+
model.Name = model.ID
|
| 154 |
+
}
|
| 155 |
+
models = append(models, model)
|
| 156 |
+
}
|
| 157 |
+
for _, model := range p.Models {
|
| 158 |
+
if seen[model.ID] {
|
| 159 |
+
continue
|
| 160 |
+
}
|
| 161 |
+
seen[model.ID] = true
|
| 162 |
+
if model.Name == "" {
|
| 163 |
+
model.Name = model.ID
|
| 164 |
+
}
|
| 165 |
+
models = append(models, model)
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
p.Models = models
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
headers := map[string]string{}
|
| 173 |
+
if len(p.DefaultHeaders) > 0 {
|
| 174 |
+
maps.Copy(headers, p.DefaultHeaders)
|
| 175 |
+
}
|
| 176 |
+
if len(config.ExtraHeaders) > 0 {
|
| 177 |
+
maps.Copy(headers, config.ExtraHeaders)
|
| 178 |
+
}
|
| 179 |
+
prepared := ProviderConfig{
|
| 180 |
+
ID: string(p.ID),
|
| 181 |
+
Name: p.Name,
|
| 182 |
+
BaseURL: p.APIEndpoint,
|
| 183 |
+
APIKey: p.APIKey,
|
| 184 |
+
Type: p.Type,
|
| 185 |
+
Disable: config.Disable,
|
| 186 |
+
SystemPromptPrefix: config.SystemPromptPrefix,
|
| 187 |
+
ExtraHeaders: headers,
|
| 188 |
+
ExtraBody: config.ExtraBody,
|
| 189 |
+
ExtraParams: make(map[string]string),
|
| 190 |
+
Models: p.Models,
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
switch p.ID {
|
| 194 |
+
// Handle specific providers that require additional configuration
|
| 195 |
+
case catwalk.InferenceProviderVertexAI:
|
| 196 |
+
if !hasVertexCredentials(env) {
|
| 197 |
+
if configExists {
|
| 198 |
+
slog.Warn("Skipping Vertex AI provider due to missing credentials")
|
| 199 |
+
c.Providers.Del(string(p.ID))
|
| 200 |
+
}
|
| 201 |
+
continue
|
| 202 |
+
}
|
| 203 |
+
prepared.ExtraParams["project"] = env.Get("VERTEXAI_PROJECT")
|
| 204 |
+
prepared.ExtraParams["location"] = env.Get("VERTEXAI_LOCATION")
|
| 205 |
+
case catwalk.InferenceProviderAzure:
|
| 206 |
+
endpoint, err := resolver.ResolveValue(p.APIEndpoint)
|
| 207 |
+
if err != nil || endpoint == "" {
|
| 208 |
+
if configExists {
|
| 209 |
+
slog.Warn("Skipping Azure provider due to missing API endpoint", "provider", p.ID, "error", err)
|
| 210 |
+
c.Providers.Del(string(p.ID))
|
| 211 |
+
}
|
| 212 |
+
continue
|
| 213 |
+
}
|
| 214 |
+
prepared.BaseURL = endpoint
|
| 215 |
+
prepared.ExtraParams["apiVersion"] = env.Get("AZURE_OPENAI_API_VERSION")
|
| 216 |
+
case catwalk.InferenceProviderBedrock:
|
| 217 |
+
if !hasAWSCredentials(env) {
|
| 218 |
+
if configExists {
|
| 219 |
+
slog.Warn("Skipping Bedrock provider due to missing AWS credentials")
|
| 220 |
+
c.Providers.Del(string(p.ID))
|
| 221 |
+
}
|
| 222 |
+
continue
|
| 223 |
+
}
|
| 224 |
+
prepared.ExtraParams["region"] = env.Get("AWS_REGION")
|
| 225 |
+
if prepared.ExtraParams["region"] == "" {
|
| 226 |
+
prepared.ExtraParams["region"] = env.Get("AWS_DEFAULT_REGION")
|
| 227 |
+
}
|
| 228 |
+
for _, model := range p.Models {
|
| 229 |
+
if !strings.HasPrefix(model.ID, "anthropic.") {
|
| 230 |
+
return fmt.Errorf("bedrock provider only supports anthropic models for now, found: %s", model.ID)
|
| 231 |
+
}
|
| 232 |
+
}
|
| 233 |
+
default:
|
| 234 |
+
// if the provider api or endpoint are missing we skip them
|
| 235 |
+
v, err := resolver.ResolveValue(p.APIKey)
|
| 236 |
+
if v == "" || err != nil {
|
| 237 |
+
if configExists {
|
| 238 |
+
slog.Warn("Skipping provider due to missing API key", "provider", p.ID)
|
| 239 |
+
c.Providers.Del(string(p.ID))
|
| 240 |
+
}
|
| 241 |
+
continue
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
c.Providers.Set(string(p.ID), prepared)
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
// validate the custom providers
|
| 248 |
+
for id, providerConfig := range c.Providers.Seq2() {
|
| 249 |
+
if knownProviderNames[id] {
|
| 250 |
+
continue
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
// Make sure the provider ID is set
|
| 254 |
+
providerConfig.ID = id
|
| 255 |
+
if providerConfig.Name == "" {
|
| 256 |
+
providerConfig.Name = id // Use ID as name if not set
|
| 257 |
+
}
|
| 258 |
+
// default to OpenAI if not set
|
| 259 |
+
if providerConfig.Type == "" {
|
| 260 |
+
providerConfig.Type = catwalk.TypeOpenAI
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
if providerConfig.Disable {
|
| 264 |
+
slog.Debug("Skipping custom provider due to disable flag", "provider", id)
|
| 265 |
+
c.Providers.Del(id)
|
| 266 |
+
continue
|
| 267 |
+
}
|
| 268 |
+
if providerConfig.APIKey == "" {
|
| 269 |
+
slog.Warn("Provider is missing API key, this might be OK for local providers", "provider", id)
|
| 270 |
+
}
|
| 271 |
+
if providerConfig.BaseURL == "" {
|
| 272 |
+
slog.Warn("Skipping custom provider due to missing API endpoint", "provider", id)
|
| 273 |
+
c.Providers.Del(id)
|
| 274 |
+
continue
|
| 275 |
+
}
|
| 276 |
+
if len(providerConfig.Models) == 0 {
|
| 277 |
+
slog.Warn("Skipping custom provider because the provider has no models", "provider", id)
|
| 278 |
+
c.Providers.Del(id)
|
| 279 |
+
continue
|
| 280 |
+
}
|
| 281 |
+
if providerConfig.Type != catwalk.TypeOpenAI && providerConfig.Type != catwalk.TypeAnthropic {
|
| 282 |
+
slog.Warn("Skipping custom provider because the provider type is not supported", "provider", id, "type", providerConfig.Type)
|
| 283 |
+
c.Providers.Del(id)
|
| 284 |
+
continue
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
apiKey, err := resolver.ResolveValue(providerConfig.APIKey)
|
| 288 |
+
if apiKey == "" || err != nil {
|
| 289 |
+
slog.Warn("Provider is missing API key, this might be OK for local providers", "provider", id)
|
| 290 |
+
}
|
| 291 |
+
baseURL, err := resolver.ResolveValue(providerConfig.BaseURL)
|
| 292 |
+
if baseURL == "" || err != nil {
|
| 293 |
+
slog.Warn("Skipping custom provider due to missing API endpoint", "provider", id, "error", err)
|
| 294 |
+
c.Providers.Del(id)
|
| 295 |
+
continue
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
c.Providers.Set(id, providerConfig)
|
| 299 |
+
}
|
| 300 |
+
return nil
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
func (c *Config) setDefaults(workingDir, dataDir string) {
|
| 304 |
+
c.workingDir = workingDir
|
| 305 |
+
if c.Options == nil {
|
| 306 |
+
c.Options = &Options{}
|
| 307 |
+
}
|
| 308 |
+
if c.Options.TUI == nil {
|
| 309 |
+
c.Options.TUI = &TUIOptions{}
|
| 310 |
+
}
|
| 311 |
+
if c.Options.ContextPaths == nil {
|
| 312 |
+
c.Options.ContextPaths = []string{}
|
| 313 |
+
}
|
| 314 |
+
if dataDir != "" {
|
| 315 |
+
c.Options.DataDirectory = dataDir
|
| 316 |
+
} else if c.Options.DataDirectory == "" {
|
| 317 |
+
if path, ok := fsext.SearchParent(workingDir, defaultDataDirectory); ok {
|
| 318 |
+
c.Options.DataDirectory = path
|
| 319 |
+
} else {
|
| 320 |
+
c.Options.DataDirectory = filepath.Join(workingDir, defaultDataDirectory)
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
if c.Providers == nil {
|
| 324 |
+
c.Providers = csync.NewMap[string, ProviderConfig]()
|
| 325 |
+
}
|
| 326 |
+
if c.Models == nil {
|
| 327 |
+
c.Models = make(map[SelectedModelType]SelectedModel)
|
| 328 |
+
}
|
| 329 |
+
if c.MCP == nil {
|
| 330 |
+
c.MCP = make(map[string]MCPConfig)
|
| 331 |
+
}
|
| 332 |
+
if c.LSP == nil {
|
| 333 |
+
c.LSP = make(map[string]LSPConfig)
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
// Apply default file types for known LSP servers if not specified
|
| 337 |
+
applyDefaultLSPFileTypes(c.LSP)
|
| 338 |
+
|
| 339 |
+
// Add the default context paths if they are not already present
|
| 340 |
+
c.Options.ContextPaths = append(defaultContextPaths, c.Options.ContextPaths...)
|
| 341 |
+
slices.Sort(c.Options.ContextPaths)
|
| 342 |
+
c.Options.ContextPaths = slices.Compact(c.Options.ContextPaths)
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
var defaultLSPFileTypes = map[string][]string{
|
| 346 |
+
"gopls": {"go", "mod", "sum", "work"},
|
| 347 |
+
"typescript-language-server": {"ts", "tsx", "js", "jsx", "mjs", "cjs"},
|
| 348 |
+
"vtsls": {"ts", "tsx", "js", "jsx", "mjs", "cjs"},
|
| 349 |
+
"bash-language-server": {"sh", "bash", "zsh", "ksh"},
|
| 350 |
+
"rust-analyzer": {"rs"},
|
| 351 |
+
"pyright": {"py", "pyi"},
|
| 352 |
+
"pylsp": {"py", "pyi"},
|
| 353 |
+
"clangd": {"c", "cpp", "cc", "cxx", "h", "hpp"},
|
| 354 |
+
"jdtls": {"java"},
|
| 355 |
+
"vscode-html-languageserver": {"html", "htm"},
|
| 356 |
+
"vscode-css-languageserver": {"css", "scss", "sass", "less"},
|
| 357 |
+
"vscode-json-languageserver": {"json", "jsonc"},
|
| 358 |
+
"yaml-language-server": {"yaml", "yml"},
|
| 359 |
+
"lua-language-server": {"lua"},
|
| 360 |
+
"solargraph": {"rb"},
|
| 361 |
+
"elixir-ls": {"ex", "exs"},
|
| 362 |
+
"zls": {"zig"},
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
// applyDefaultLSPFileTypes sets default file types for known LSP servers
|
| 366 |
+
func applyDefaultLSPFileTypes(lspConfigs map[string]LSPConfig) {
|
| 367 |
+
for name, config := range lspConfigs {
|
| 368 |
+
if len(config.FileTypes) != 0 {
|
| 369 |
+
continue
|
| 370 |
+
}
|
| 371 |
+
bin := strings.ToLower(filepath.Base(config.Command))
|
| 372 |
+
config.FileTypes = defaultLSPFileTypes[bin]
|
| 373 |
+
lspConfigs[name] = config
|
| 374 |
+
}
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
func (c *Config) defaultModelSelection(knownProviders []catwalk.Provider) (largeModel SelectedModel, smallModel SelectedModel, err error) {
|
| 378 |
+
if len(knownProviders) == 0 && c.Providers.Len() == 0 {
|
| 379 |
+
err = fmt.Errorf("no providers configured, please configure at least one provider")
|
| 380 |
+
return
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
// Use the first provider enabled based on the known providers order
|
| 384 |
+
// if no provider found that is known use the first provider configured
|
| 385 |
+
for _, p := range knownProviders {
|
| 386 |
+
providerConfig, ok := c.Providers.Get(string(p.ID))
|
| 387 |
+
if !ok || providerConfig.Disable {
|
| 388 |
+
continue
|
| 389 |
+
}
|
| 390 |
+
defaultLargeModel := c.GetModel(string(p.ID), p.DefaultLargeModelID)
|
| 391 |
+
if defaultLargeModel == nil {
|
| 392 |
+
err = fmt.Errorf("default large model %s not found for provider %s", p.DefaultLargeModelID, p.ID)
|
| 393 |
+
return
|
| 394 |
+
}
|
| 395 |
+
largeModel = SelectedModel{
|
| 396 |
+
Provider: string(p.ID),
|
| 397 |
+
Model: defaultLargeModel.ID,
|
| 398 |
+
MaxTokens: defaultLargeModel.DefaultMaxTokens,
|
| 399 |
+
ReasoningEffort: defaultLargeModel.DefaultReasoningEffort,
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
defaultSmallModel := c.GetModel(string(p.ID), p.DefaultSmallModelID)
|
| 403 |
+
if defaultSmallModel == nil {
|
| 404 |
+
err = fmt.Errorf("default small model %s not found for provider %s", p.DefaultSmallModelID, p.ID)
|
| 405 |
+
return
|
| 406 |
+
}
|
| 407 |
+
smallModel = SelectedModel{
|
| 408 |
+
Provider: string(p.ID),
|
| 409 |
+
Model: defaultSmallModel.ID,
|
| 410 |
+
MaxTokens: defaultSmallModel.DefaultMaxTokens,
|
| 411 |
+
ReasoningEffort: defaultSmallModel.DefaultReasoningEffort,
|
| 412 |
+
}
|
| 413 |
+
return
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
enabledProviders := c.EnabledProviders()
|
| 417 |
+
slices.SortFunc(enabledProviders, func(a, b ProviderConfig) int {
|
| 418 |
+
return strings.Compare(a.ID, b.ID)
|
| 419 |
+
})
|
| 420 |
+
|
| 421 |
+
if len(enabledProviders) == 0 {
|
| 422 |
+
err = fmt.Errorf("no providers configured, please configure at least one provider")
|
| 423 |
+
return
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
providerConfig := enabledProviders[0]
|
| 427 |
+
if len(providerConfig.Models) == 0 {
|
| 428 |
+
err = fmt.Errorf("provider %s has no models configured", providerConfig.ID)
|
| 429 |
+
return
|
| 430 |
+
}
|
| 431 |
+
defaultLargeModel := c.GetModel(providerConfig.ID, providerConfig.Models[0].ID)
|
| 432 |
+
largeModel = SelectedModel{
|
| 433 |
+
Provider: providerConfig.ID,
|
| 434 |
+
Model: defaultLargeModel.ID,
|
| 435 |
+
MaxTokens: defaultLargeModel.DefaultMaxTokens,
|
| 436 |
+
}
|
| 437 |
+
defaultSmallModel := c.GetModel(providerConfig.ID, providerConfig.Models[0].ID)
|
| 438 |
+
smallModel = SelectedModel{
|
| 439 |
+
Provider: providerConfig.ID,
|
| 440 |
+
Model: defaultSmallModel.ID,
|
| 441 |
+
MaxTokens: defaultSmallModel.DefaultMaxTokens,
|
| 442 |
+
}
|
| 443 |
+
return
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
func (c *Config) configureSelectedModels(knownProviders []catwalk.Provider) error {
|
| 447 |
+
defaultLarge, defaultSmall, err := c.defaultModelSelection(knownProviders)
|
| 448 |
+
if err != nil {
|
| 449 |
+
return fmt.Errorf("failed to select default models: %w", err)
|
| 450 |
+
}
|
| 451 |
+
large, small := defaultLarge, defaultSmall
|
| 452 |
+
|
| 453 |
+
largeModelSelected, largeModelConfigured := c.Models[SelectedModelTypeLarge]
|
| 454 |
+
if largeModelConfigured {
|
| 455 |
+
if largeModelSelected.Model != "" {
|
| 456 |
+
large.Model = largeModelSelected.Model
|
| 457 |
+
}
|
| 458 |
+
if largeModelSelected.Provider != "" {
|
| 459 |
+
large.Provider = largeModelSelected.Provider
|
| 460 |
+
}
|
| 461 |
+
model := c.GetModel(large.Provider, large.Model)
|
| 462 |
+
if model == nil {
|
| 463 |
+
large = defaultLarge
|
| 464 |
+
// override the model type to large
|
| 465 |
+
err := c.UpdatePreferredModel(SelectedModelTypeLarge, large)
|
| 466 |
+
if err != nil {
|
| 467 |
+
return fmt.Errorf("failed to update preferred large model: %w", err)
|
| 468 |
+
}
|
| 469 |
+
} else {
|
| 470 |
+
if largeModelSelected.MaxTokens > 0 {
|
| 471 |
+
large.MaxTokens = largeModelSelected.MaxTokens
|
| 472 |
+
} else {
|
| 473 |
+
large.MaxTokens = model.DefaultMaxTokens
|
| 474 |
+
}
|
| 475 |
+
if largeModelSelected.ReasoningEffort != "" {
|
| 476 |
+
large.ReasoningEffort = largeModelSelected.ReasoningEffort
|
| 477 |
+
}
|
| 478 |
+
large.Think = largeModelSelected.Think
|
| 479 |
+
}
|
| 480 |
+
}
|
| 481 |
+
smallModelSelected, smallModelConfigured := c.Models[SelectedModelTypeSmall]
|
| 482 |
+
if smallModelConfigured {
|
| 483 |
+
if smallModelSelected.Model != "" {
|
| 484 |
+
small.Model = smallModelSelected.Model
|
| 485 |
+
}
|
| 486 |
+
if smallModelSelected.Provider != "" {
|
| 487 |
+
small.Provider = smallModelSelected.Provider
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
model := c.GetModel(small.Provider, small.Model)
|
| 491 |
+
if model == nil {
|
| 492 |
+
small = defaultSmall
|
| 493 |
+
// override the model type to small
|
| 494 |
+
err := c.UpdatePreferredModel(SelectedModelTypeSmall, small)
|
| 495 |
+
if err != nil {
|
| 496 |
+
return fmt.Errorf("failed to update preferred small model: %w", err)
|
| 497 |
+
}
|
| 498 |
+
} else {
|
| 499 |
+
if smallModelSelected.MaxTokens > 0 {
|
| 500 |
+
small.MaxTokens = smallModelSelected.MaxTokens
|
| 501 |
+
} else {
|
| 502 |
+
small.MaxTokens = model.DefaultMaxTokens
|
| 503 |
+
}
|
| 504 |
+
small.ReasoningEffort = smallModelSelected.ReasoningEffort
|
| 505 |
+
small.Think = smallModelSelected.Think
|
| 506 |
+
}
|
| 507 |
+
}
|
| 508 |
+
c.Models[SelectedModelTypeLarge] = large
|
| 509 |
+
c.Models[SelectedModelTypeSmall] = small
|
| 510 |
+
return nil
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
func loadFromConfigPaths(configPaths []string) (*Config, error) {
|
| 514 |
+
var configs []io.Reader
|
| 515 |
+
|
| 516 |
+
for _, path := range configPaths {
|
| 517 |
+
fd, err := os.Open(path)
|
| 518 |
+
if err != nil {
|
| 519 |
+
if os.IsNotExist(err) {
|
| 520 |
+
continue
|
| 521 |
+
}
|
| 522 |
+
return nil, fmt.Errorf("failed to open config file %s: %w", path, err)
|
| 523 |
+
}
|
| 524 |
+
defer fd.Close()
|
| 525 |
+
|
| 526 |
+
configs = append(configs, fd)
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
return loadFromReaders(configs)
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
func loadFromReaders(readers []io.Reader) (*Config, error) {
|
| 533 |
+
if len(readers) == 0 {
|
| 534 |
+
return &Config{}, nil
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
merged, err := Merge(readers)
|
| 538 |
+
if err != nil {
|
| 539 |
+
return nil, fmt.Errorf("failed to merge configuration readers: %w", err)
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
return LoadReader(merged)
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
func hasVertexCredentials(env env.Env) bool {
|
| 546 |
+
hasProject := env.Get("VERTEXAI_PROJECT") != ""
|
| 547 |
+
hasLocation := env.Get("VERTEXAI_LOCATION") != ""
|
| 548 |
+
return hasProject && hasLocation
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
func hasAWSCredentials(env env.Env) bool {
|
| 552 |
+
if env.Get("AWS_ACCESS_KEY_ID") != "" && env.Get("AWS_SECRET_ACCESS_KEY") != "" {
|
| 553 |
+
return true
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
if env.Get("AWS_PROFILE") != "" || env.Get("AWS_DEFAULT_PROFILE") != "" {
|
| 557 |
+
return true
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
if env.Get("AWS_REGION") != "" || env.Get("AWS_DEFAULT_REGION") != "" {
|
| 561 |
+
return true
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
if env.Get("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") != "" ||
|
| 565 |
+
env.Get("AWS_CONTAINER_CREDENTIALS_FULL_URI") != "" {
|
| 566 |
+
return true
|
| 567 |
+
}
|
| 568 |
+
return false
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
func globalConfig() string {
|
| 572 |
+
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
|
| 573 |
+
if xdgConfigHome != "" {
|
| 574 |
+
return filepath.Join(xdgConfigHome, appName, fmt.Sprintf("%s.json", appName))
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
// return the path to the main config directory
|
| 578 |
+
// for windows, it should be in `%LOCALAPPDATA%/crush/`
|
| 579 |
+
// for linux and macOS, it should be in `$HOME/.config/crush/`
|
| 580 |
+
if runtime.GOOS == "windows" {
|
| 581 |
+
localAppData := os.Getenv("LOCALAPPDATA")
|
| 582 |
+
if localAppData == "" {
|
| 583 |
+
localAppData = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
|
| 584 |
+
}
|
| 585 |
+
return filepath.Join(localAppData, appName, fmt.Sprintf("%s.json", appName))
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
return filepath.Join(home.Dir(), ".config", appName, fmt.Sprintf("%s.json", appName))
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
// GlobalConfigData returns the path to the main data directory for the application.
|
| 592 |
+
// this config is used when the app overrides configurations instead of updating the global config.
|
| 593 |
+
func GlobalConfigData() string {
|
| 594 |
+
xdgDataHome := os.Getenv("XDG_DATA_HOME")
|
| 595 |
+
if xdgDataHome != "" {
|
| 596 |
+
return filepath.Join(xdgDataHome, appName, fmt.Sprintf("%s.json", appName))
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
+
// return the path to the main data directory
|
| 600 |
+
// for windows, it should be in `%LOCALAPPDATA%/crush/`
|
| 601 |
+
// for linux and macOS, it should be in `$HOME/.local/share/crush/`
|
| 602 |
+
if runtime.GOOS == "windows" {
|
| 603 |
+
localAppData := os.Getenv("LOCALAPPDATA")
|
| 604 |
+
if localAppData == "" {
|
| 605 |
+
localAppData = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
|
| 606 |
+
}
|
| 607 |
+
return filepath.Join(localAppData, appName, fmt.Sprintf("%s.json", appName))
|
| 608 |
+
}
|
| 609 |
+
|
| 610 |
+
return filepath.Join(home.D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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"io"
|
| 5 |
+
"log/slog"
|
| 6 |
+
"os"
|
| 7 |
+
"path/filepath"
|
| 8 |
+
"strings"
|
| 9 |
+
"testing"
|
| 10 |
+
|
| 11 |
+
"github.com/charmbracelet/catwalk/pkg/catwalk"
|
| 12 |
+
"github.com/charmbracelet/crush/internal/csync"
|
| 13 |
+
"github.com/charmbracelet/crush/internal/env"
|
| 14 |
+
"github.com/stretchr/testify/require"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
func TestMain(m *testing.M) {
|
| 18 |
+
slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))
|
| 19 |
+
|
| 20 |
+
exitVal := m.Run()
|
| 21 |
+
os.Exit(exitVal)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func TestConfig_LoadFromReaders(t *testing.T) {
|
| 25 |
+
data1 := strings.NewReader(`{"providers": {"openai": {"api_key": "key1", "base_url": "https://api.openai.com/v1"}}}`)
|
| 26 |
+
data2 := strings.NewReader(`{"providers": {"openai": {"api_key": "key2", "base_url": "https://api.openai.com/v2"}}}`)
|
| 27 |
+
data3 := strings.NewReader(`{"providers": {"openai": {}}}`)
|
| 28 |
+
|
| 29 |
+
loadedConfig, err := loadFromReaders([]io.Reader{data1, data2, data3})
|
| 30 |
+
|
| 31 |
+
require.NoError(t, err)
|
| 32 |
+
require.NotNil(t, loadedConfig)
|
| 33 |
+
require.Equal(t, 1, loadedConfig.Providers.Len())
|
| 34 |
+
pc, _ := loadedConfig.Providers.Get("openai")
|
| 35 |
+
require.Equal(t, "key2", pc.APIKey)
|
| 36 |
+
require.Equal(t, "https://api.openai.com/v2", pc.BaseURL)
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
func TestConfig_setDefaults(t *testing.T) {
|
| 40 |
+
cfg := &Config{}
|
| 41 |
+
|
| 42 |
+
cfg.setDefaults("/tmp", "")
|
| 43 |
+
|
| 44 |
+
require.NotNil(t, cfg.Options)
|
| 45 |
+
require.NotNil(t, cfg.Options.TUI)
|
| 46 |
+
require.NotNil(t, cfg.Options.ContextPaths)
|
| 47 |
+
require.NotNil(t, cfg.Providers)
|
| 48 |
+
require.NotNil(t, cfg.Models)
|
| 49 |
+
require.NotNil(t, cfg.LSP)
|
| 50 |
+
require.NotNil(t, cfg.MCP)
|
| 51 |
+
require.Equal(t, filepath.Join("/tmp", ".crush"), cfg.Options.DataDirectory)
|
| 52 |
+
for _, path := range defaultContextPaths {
|
| 53 |
+
require.Contains(t, cfg.Options.ContextPaths, path)
|
| 54 |
+
}
|
| 55 |
+
require.Equal(t, "/tmp", cfg.workingDir)
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
func TestConfig_configureProviders(t *testing.T) {
|
| 59 |
+
knownProviders := []catwalk.Provider{
|
| 60 |
+
{
|
| 61 |
+
ID: "openai",
|
| 62 |
+
APIKey: "$OPENAI_API_KEY",
|
| 63 |
+
APIEndpoint: "https://api.openai.com/v1",
|
| 64 |
+
Models: []catwalk.Model{{
|
| 65 |
+
ID: "test-model",
|
| 66 |
+
}},
|
| 67 |
+
},
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
cfg := &Config{}
|
| 71 |
+
cfg.setDefaults("/tmp", "")
|
| 72 |
+
env := env.NewFromMap(map[string]string{
|
| 73 |
+
"OPENAI_API_KEY": "test-key",
|
| 74 |
+
})
|
| 75 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 76 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 77 |
+
require.NoError(t, err)
|
| 78 |
+
require.Equal(t, 1, cfg.Providers.Len())
|
| 79 |
+
|
| 80 |
+
// We want to make sure that we keep the configured API key as a placeholder
|
| 81 |
+
pc, _ := cfg.Providers.Get("openai")
|
| 82 |
+
require.Equal(t, "$OPENAI_API_KEY", pc.APIKey)
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
func TestConfig_configureProvidersWithOverride(t *testing.T) {
|
| 86 |
+
knownProviders := []catwalk.Provider{
|
| 87 |
+
{
|
| 88 |
+
ID: "openai",
|
| 89 |
+
APIKey: "$OPENAI_API_KEY",
|
| 90 |
+
APIEndpoint: "https://api.openai.com/v1",
|
| 91 |
+
Models: []catwalk.Model{{
|
| 92 |
+
ID: "test-model",
|
| 93 |
+
}},
|
| 94 |
+
},
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
cfg := &Config{
|
| 98 |
+
Providers: csync.NewMap[string, ProviderConfig](),
|
| 99 |
+
}
|
| 100 |
+
cfg.Providers.Set("openai", ProviderConfig{
|
| 101 |
+
APIKey: "xyz",
|
| 102 |
+
BaseURL: "https://api.openai.com/v2",
|
| 103 |
+
Models: []catwalk.Model{
|
| 104 |
+
{
|
| 105 |
+
ID: "test-model",
|
| 106 |
+
Name: "Updated",
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
ID: "another-model",
|
| 110 |
+
},
|
| 111 |
+
},
|
| 112 |
+
})
|
| 113 |
+
cfg.setDefaults("/tmp", "")
|
| 114 |
+
|
| 115 |
+
env := env.NewFromMap(map[string]string{
|
| 116 |
+
"OPENAI_API_KEY": "test-key",
|
| 117 |
+
})
|
| 118 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 119 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 120 |
+
require.NoError(t, err)
|
| 121 |
+
require.Equal(t, 1, cfg.Providers.Len())
|
| 122 |
+
|
| 123 |
+
// We want to make sure that we keep the configured API key as a placeholder
|
| 124 |
+
pc, _ := cfg.Providers.Get("openai")
|
| 125 |
+
require.Equal(t, "xyz", pc.APIKey)
|
| 126 |
+
require.Equal(t, "https://api.openai.com/v2", pc.BaseURL)
|
| 127 |
+
require.Len(t, pc.Models, 2)
|
| 128 |
+
require.Equal(t, "Updated", pc.Models[0].Name)
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
func TestConfig_configureProvidersWithNewProvider(t *testing.T) {
|
| 132 |
+
knownProviders := []catwalk.Provider{
|
| 133 |
+
{
|
| 134 |
+
ID: "openai",
|
| 135 |
+
APIKey: "$OPENAI_API_KEY",
|
| 136 |
+
APIEndpoint: "https://api.openai.com/v1",
|
| 137 |
+
Models: []catwalk.Model{{
|
| 138 |
+
ID: "test-model",
|
| 139 |
+
}},
|
| 140 |
+
},
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
cfg := &Config{
|
| 144 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 145 |
+
"custom": {
|
| 146 |
+
APIKey: "xyz",
|
| 147 |
+
BaseURL: "https://api.someendpoint.com/v2",
|
| 148 |
+
Models: []catwalk.Model{
|
| 149 |
+
{
|
| 150 |
+
ID: "test-model",
|
| 151 |
+
},
|
| 152 |
+
},
|
| 153 |
+
},
|
| 154 |
+
}),
|
| 155 |
+
}
|
| 156 |
+
cfg.setDefaults("/tmp", "")
|
| 157 |
+
env := env.NewFromMap(map[string]string{
|
| 158 |
+
"OPENAI_API_KEY": "test-key",
|
| 159 |
+
})
|
| 160 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 161 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 162 |
+
require.NoError(t, err)
|
| 163 |
+
// Should be to because of the env variable
|
| 164 |
+
require.Equal(t, cfg.Providers.Len(), 2)
|
| 165 |
+
|
| 166 |
+
// We want to make sure that we keep the configured API key as a placeholder
|
| 167 |
+
pc, _ := cfg.Providers.Get("custom")
|
| 168 |
+
require.Equal(t, "xyz", pc.APIKey)
|
| 169 |
+
// Make sure we set the ID correctly
|
| 170 |
+
require.Equal(t, "custom", pc.ID)
|
| 171 |
+
require.Equal(t, "https://api.someendpoint.com/v2", pc.BaseURL)
|
| 172 |
+
require.Len(t, pc.Models, 1)
|
| 173 |
+
|
| 174 |
+
_, ok := cfg.Providers.Get("openai")
|
| 175 |
+
require.True(t, ok, "OpenAI provider should still be present")
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
func TestConfig_configureProvidersBedrockWithCredentials(t *testing.T) {
|
| 179 |
+
knownProviders := []catwalk.Provider{
|
| 180 |
+
{
|
| 181 |
+
ID: catwalk.InferenceProviderBedrock,
|
| 182 |
+
APIKey: "",
|
| 183 |
+
APIEndpoint: "",
|
| 184 |
+
Models: []catwalk.Model{{
|
| 185 |
+
ID: "anthropic.claude-sonnet-4-20250514-v1:0",
|
| 186 |
+
}},
|
| 187 |
+
},
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
cfg := &Config{}
|
| 191 |
+
cfg.setDefaults("/tmp", "")
|
| 192 |
+
env := env.NewFromMap(map[string]string{
|
| 193 |
+
"AWS_ACCESS_KEY_ID": "test-key-id",
|
| 194 |
+
"AWS_SECRET_ACCESS_KEY": "test-secret-key",
|
| 195 |
+
})
|
| 196 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 197 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 198 |
+
require.NoError(t, err)
|
| 199 |
+
require.Equal(t, cfg.Providers.Len(), 1)
|
| 200 |
+
|
| 201 |
+
bedrockProvider, ok := cfg.Providers.Get("bedrock")
|
| 202 |
+
require.True(t, ok, "Bedrock provider should be present")
|
| 203 |
+
require.Len(t, bedrockProvider.Models, 1)
|
| 204 |
+
require.Equal(t, "anthropic.claude-sonnet-4-20250514-v1:0", bedrockProvider.Models[0].ID)
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
func TestConfig_configureProvidersBedrockWithoutCredentials(t *testing.T) {
|
| 208 |
+
knownProviders := []catwalk.Provider{
|
| 209 |
+
{
|
| 210 |
+
ID: catwalk.InferenceProviderBedrock,
|
| 211 |
+
APIKey: "",
|
| 212 |
+
APIEndpoint: "",
|
| 213 |
+
Models: []catwalk.Model{{
|
| 214 |
+
ID: "anthropic.claude-sonnet-4-20250514-v1:0",
|
| 215 |
+
}},
|
| 216 |
+
},
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
cfg := &Config{}
|
| 220 |
+
cfg.setDefaults("/tmp", "")
|
| 221 |
+
env := env.NewFromMap(map[string]string{})
|
| 222 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 223 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 224 |
+
require.NoError(t, err)
|
| 225 |
+
// Provider should not be configured without credentials
|
| 226 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
func TestConfig_configureProvidersBedrockWithoutUnsupportedModel(t *testing.T) {
|
| 230 |
+
knownProviders := []catwalk.Provider{
|
| 231 |
+
{
|
| 232 |
+
ID: catwalk.InferenceProviderBedrock,
|
| 233 |
+
APIKey: "",
|
| 234 |
+
APIEndpoint: "",
|
| 235 |
+
Models: []catwalk.Model{{
|
| 236 |
+
ID: "some-random-model",
|
| 237 |
+
}},
|
| 238 |
+
},
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
cfg := &Config{}
|
| 242 |
+
cfg.setDefaults("/tmp", "")
|
| 243 |
+
env := env.NewFromMap(map[string]string{
|
| 244 |
+
"AWS_ACCESS_KEY_ID": "test-key-id",
|
| 245 |
+
"AWS_SECRET_ACCESS_KEY": "test-secret-key",
|
| 246 |
+
})
|
| 247 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 248 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 249 |
+
require.Error(t, err)
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
func TestConfig_configureProvidersVertexAIWithCredentials(t *testing.T) {
|
| 253 |
+
knownProviders := []catwalk.Provider{
|
| 254 |
+
{
|
| 255 |
+
ID: catwalk.InferenceProviderVertexAI,
|
| 256 |
+
APIKey: "",
|
| 257 |
+
APIEndpoint: "",
|
| 258 |
+
Models: []catwalk.Model{{
|
| 259 |
+
ID: "gemini-pro",
|
| 260 |
+
}},
|
| 261 |
+
},
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
cfg := &Config{}
|
| 265 |
+
cfg.setDefaults("/tmp", "")
|
| 266 |
+
env := env.NewFromMap(map[string]string{
|
| 267 |
+
"VERTEXAI_PROJECT": "test-project",
|
| 268 |
+
"VERTEXAI_LOCATION": "us-central1",
|
| 269 |
+
})
|
| 270 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 271 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 272 |
+
require.NoError(t, err)
|
| 273 |
+
require.Equal(t, cfg.Providers.Len(), 1)
|
| 274 |
+
|
| 275 |
+
vertexProvider, ok := cfg.Providers.Get("vertexai")
|
| 276 |
+
require.True(t, ok, "VertexAI provider should be present")
|
| 277 |
+
require.Len(t, vertexProvider.Models, 1)
|
| 278 |
+
require.Equal(t, "gemini-pro", vertexProvider.Models[0].ID)
|
| 279 |
+
require.Equal(t, "test-project", vertexProvider.ExtraParams["project"])
|
| 280 |
+
require.Equal(t, "us-central1", vertexProvider.ExtraParams["location"])
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
func TestConfig_configureProvidersVertexAIWithoutCredentials(t *testing.T) {
|
| 284 |
+
knownProviders := []catwalk.Provider{
|
| 285 |
+
{
|
| 286 |
+
ID: catwalk.InferenceProviderVertexAI,
|
| 287 |
+
APIKey: "",
|
| 288 |
+
APIEndpoint: "",
|
| 289 |
+
Models: []catwalk.Model{{
|
| 290 |
+
ID: "gemini-pro",
|
| 291 |
+
}},
|
| 292 |
+
},
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
cfg := &Config{}
|
| 296 |
+
cfg.setDefaults("/tmp", "")
|
| 297 |
+
env := env.NewFromMap(map[string]string{
|
| 298 |
+
"GOOGLE_GENAI_USE_VERTEXAI": "false",
|
| 299 |
+
"GOOGLE_CLOUD_PROJECT": "test-project",
|
| 300 |
+
"GOOGLE_CLOUD_LOCATION": "us-central1",
|
| 301 |
+
})
|
| 302 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 303 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 304 |
+
require.NoError(t, err)
|
| 305 |
+
// Provider should not be configured without proper credentials
|
| 306 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
func TestConfig_configureProvidersVertexAIMissingProject(t *testing.T) {
|
| 310 |
+
knownProviders := []catwalk.Provider{
|
| 311 |
+
{
|
| 312 |
+
ID: catwalk.InferenceProviderVertexAI,
|
| 313 |
+
APIKey: "",
|
| 314 |
+
APIEndpoint: "",
|
| 315 |
+
Models: []catwalk.Model{{
|
| 316 |
+
ID: "gemini-pro",
|
| 317 |
+
}},
|
| 318 |
+
},
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
cfg := &Config{}
|
| 322 |
+
cfg.setDefaults("/tmp", "")
|
| 323 |
+
env := env.NewFromMap(map[string]string{
|
| 324 |
+
"GOOGLE_GENAI_USE_VERTEXAI": "true",
|
| 325 |
+
"GOOGLE_CLOUD_LOCATION": "us-central1",
|
| 326 |
+
})
|
| 327 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 328 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 329 |
+
require.NoError(t, err)
|
| 330 |
+
// Provider should not be configured without project
|
| 331 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
func TestConfig_configureProvidersSetProviderID(t *testing.T) {
|
| 335 |
+
knownProviders := []catwalk.Provider{
|
| 336 |
+
{
|
| 337 |
+
ID: "openai",
|
| 338 |
+
APIKey: "$OPENAI_API_KEY",
|
| 339 |
+
APIEndpoint: "https://api.openai.com/v1",
|
| 340 |
+
Models: []catwalk.Model{{
|
| 341 |
+
ID: "test-model",
|
| 342 |
+
}},
|
| 343 |
+
},
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
cfg := &Config{}
|
| 347 |
+
cfg.setDefaults("/tmp", "")
|
| 348 |
+
env := env.NewFromMap(map[string]string{
|
| 349 |
+
"OPENAI_API_KEY": "test-key",
|
| 350 |
+
})
|
| 351 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 352 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 353 |
+
require.NoError(t, err)
|
| 354 |
+
require.Equal(t, cfg.Providers.Len(), 1)
|
| 355 |
+
|
| 356 |
+
// Provider ID should be set
|
| 357 |
+
pc, _ := cfg.Providers.Get("openai")
|
| 358 |
+
require.Equal(t, "openai", pc.ID)
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
func TestConfig_EnabledProviders(t *testing.T) {
|
| 362 |
+
t.Run("all providers enabled", func(t *testing.T) {
|
| 363 |
+
cfg := &Config{
|
| 364 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 365 |
+
"openai": {
|
| 366 |
+
ID: "openai",
|
| 367 |
+
APIKey: "key1",
|
| 368 |
+
Disable: false,
|
| 369 |
+
},
|
| 370 |
+
"anthropic": {
|
| 371 |
+
ID: "anthropic",
|
| 372 |
+
APIKey: "key2",
|
| 373 |
+
Disable: false,
|
| 374 |
+
},
|
| 375 |
+
}),
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
enabled := cfg.EnabledProviders()
|
| 379 |
+
require.Len(t, enabled, 2)
|
| 380 |
+
})
|
| 381 |
+
|
| 382 |
+
t.Run("some providers disabled", func(t *testing.T) {
|
| 383 |
+
cfg := &Config{
|
| 384 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 385 |
+
"openai": {
|
| 386 |
+
ID: "openai",
|
| 387 |
+
APIKey: "key1",
|
| 388 |
+
Disable: false,
|
| 389 |
+
},
|
| 390 |
+
"anthropic": {
|
| 391 |
+
ID: "anthropic",
|
| 392 |
+
APIKey: "key2",
|
| 393 |
+
Disable: true,
|
| 394 |
+
},
|
| 395 |
+
}),
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
enabled := cfg.EnabledProviders()
|
| 399 |
+
require.Len(t, enabled, 1)
|
| 400 |
+
require.Equal(t, "openai", enabled[0].ID)
|
| 401 |
+
})
|
| 402 |
+
|
| 403 |
+
t.Run("empty providers map", func(t *testing.T) {
|
| 404 |
+
cfg := &Config{
|
| 405 |
+
Providers: csync.NewMap[string, ProviderConfig](),
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
enabled := cfg.EnabledProviders()
|
| 409 |
+
require.Len(t, enabled, 0)
|
| 410 |
+
})
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
func TestConfig_IsConfigured(t *testing.T) {
|
| 414 |
+
t.Run("returns true when at least one provider is enabled", func(t *testing.T) {
|
| 415 |
+
cfg := &Config{
|
| 416 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 417 |
+
"openai": {
|
| 418 |
+
ID: "openai",
|
| 419 |
+
APIKey: "key1",
|
| 420 |
+
Disable: false,
|
| 421 |
+
},
|
| 422 |
+
}),
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
require.True(t, cfg.IsConfigured())
|
| 426 |
+
})
|
| 427 |
+
|
| 428 |
+
t.Run("returns false when no providers are configured", func(t *testing.T) {
|
| 429 |
+
cfg := &Config{
|
| 430 |
+
Providers: csync.NewMap[string, ProviderConfig](),
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
require.False(t, cfg.IsConfigured())
|
| 434 |
+
})
|
| 435 |
+
|
| 436 |
+
t.Run("returns false when all providers are disabled", func(t *testing.T) {
|
| 437 |
+
cfg := &Config{
|
| 438 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 439 |
+
"openai": {
|
| 440 |
+
ID: "openai",
|
| 441 |
+
APIKey: "key1",
|
| 442 |
+
Disable: true,
|
| 443 |
+
},
|
| 444 |
+
"anthropic": {
|
| 445 |
+
ID: "anthropic",
|
| 446 |
+
APIKey: "key2",
|
| 447 |
+
Disable: true,
|
| 448 |
+
},
|
| 449 |
+
}),
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
require.False(t, cfg.IsConfigured())
|
| 453 |
+
})
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
func TestConfig_configureProvidersWithDisabledProvider(t *testing.T) {
|
| 457 |
+
knownProviders := []catwalk.Provider{
|
| 458 |
+
{
|
| 459 |
+
ID: "openai",
|
| 460 |
+
APIKey: "$OPENAI_API_KEY",
|
| 461 |
+
APIEndpoint: "https://api.openai.com/v1",
|
| 462 |
+
Models: []catwalk.Model{{
|
| 463 |
+
ID: "test-model",
|
| 464 |
+
}},
|
| 465 |
+
},
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
cfg := &Config{
|
| 469 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 470 |
+
"openai": {
|
| 471 |
+
Disable: true,
|
| 472 |
+
},
|
| 473 |
+
}),
|
| 474 |
+
}
|
| 475 |
+
cfg.setDefaults("/tmp", "")
|
| 476 |
+
|
| 477 |
+
env := env.NewFromMap(map[string]string{
|
| 478 |
+
"OPENAI_API_KEY": "test-key",
|
| 479 |
+
})
|
| 480 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 481 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 482 |
+
require.NoError(t, err)
|
| 483 |
+
|
| 484 |
+
// Provider should be removed from config when disabled
|
| 485 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 486 |
+
_, exists := cfg.Providers.Get("openai")
|
| 487 |
+
require.False(t, exists)
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
func TestConfig_configureProvidersCustomProviderValidation(t *testing.T) {
|
| 491 |
+
t.Run("custom provider with missing API key is allowed, but not known providers", func(t *testing.T) {
|
| 492 |
+
cfg := &Config{
|
| 493 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 494 |
+
"custom": {
|
| 495 |
+
BaseURL: "https://api.custom.com/v1",
|
| 496 |
+
Models: []catwalk.Model{{
|
| 497 |
+
ID: "test-model",
|
| 498 |
+
}},
|
| 499 |
+
},
|
| 500 |
+
"openai": {
|
| 501 |
+
APIKey: "$MISSING",
|
| 502 |
+
},
|
| 503 |
+
}),
|
| 504 |
+
}
|
| 505 |
+
cfg.setDefaults("/tmp", "")
|
| 506 |
+
|
| 507 |
+
env := env.NewFromMap(map[string]string{})
|
| 508 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 509 |
+
err := cfg.configureProviders(env, resolver, []catwalk.Provider{})
|
| 510 |
+
require.NoError(t, err)
|
| 511 |
+
|
| 512 |
+
require.Equal(t, cfg.Providers.Len(), 1)
|
| 513 |
+
_, exists := cfg.Providers.Get("custom")
|
| 514 |
+
require.True(t, exists)
|
| 515 |
+
})
|
| 516 |
+
|
| 517 |
+
t.Run("custom provider with missing BaseURL is removed", func(t *testing.T) {
|
| 518 |
+
cfg := &Config{
|
| 519 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 520 |
+
"custom": {
|
| 521 |
+
APIKey: "test-key",
|
| 522 |
+
Models: []catwalk.Model{{
|
| 523 |
+
ID: "test-model",
|
| 524 |
+
}},
|
| 525 |
+
},
|
| 526 |
+
}),
|
| 527 |
+
}
|
| 528 |
+
cfg.setDefaults("/tmp", "")
|
| 529 |
+
|
| 530 |
+
env := env.NewFromMap(map[string]string{})
|
| 531 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 532 |
+
err := cfg.configureProviders(env, resolver, []catwalk.Provider{})
|
| 533 |
+
require.NoError(t, err)
|
| 534 |
+
|
| 535 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 536 |
+
_, exists := cfg.Providers.Get("custom")
|
| 537 |
+
require.False(t, exists)
|
| 538 |
+
})
|
| 539 |
+
|
| 540 |
+
t.Run("custom provider with no models is removed", func(t *testing.T) {
|
| 541 |
+
cfg := &Config{
|
| 542 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 543 |
+
"custom": {
|
| 544 |
+
APIKey: "test-key",
|
| 545 |
+
BaseURL: "https://api.custom.com/v1",
|
| 546 |
+
Models: []catwalk.Model{},
|
| 547 |
+
},
|
| 548 |
+
}),
|
| 549 |
+
}
|
| 550 |
+
cfg.setDefaults("/tmp", "")
|
| 551 |
+
|
| 552 |
+
env := env.NewFromMap(map[string]string{})
|
| 553 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 554 |
+
err := cfg.configureProviders(env, resolver, []catwalk.Provider{})
|
| 555 |
+
require.NoError(t, err)
|
| 556 |
+
|
| 557 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 558 |
+
_, exists := cfg.Providers.Get("custom")
|
| 559 |
+
require.False(t, exists)
|
| 560 |
+
})
|
| 561 |
+
|
| 562 |
+
t.Run("custom provider with unsupported type is removed", func(t *testing.T) {
|
| 563 |
+
cfg := &Config{
|
| 564 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 565 |
+
"custom": {
|
| 566 |
+
APIKey: "test-key",
|
| 567 |
+
BaseURL: "https://api.custom.com/v1",
|
| 568 |
+
Type: "unsupported",
|
| 569 |
+
Models: []catwalk.Model{{
|
| 570 |
+
ID: "test-model",
|
| 571 |
+
}},
|
| 572 |
+
},
|
| 573 |
+
}),
|
| 574 |
+
}
|
| 575 |
+
cfg.setDefaults("/tmp", "")
|
| 576 |
+
|
| 577 |
+
env := env.NewFromMap(map[string]string{})
|
| 578 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 579 |
+
err := cfg.configureProviders(env, resolver, []catwalk.Provider{})
|
| 580 |
+
require.NoError(t, err)
|
| 581 |
+
|
| 582 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 583 |
+
_, exists := cfg.Providers.Get("custom")
|
| 584 |
+
require.False(t, exists)
|
| 585 |
+
})
|
| 586 |
+
|
| 587 |
+
t.Run("valid custom provider is kept and ID is set", func(t *testing.T) {
|
| 588 |
+
cfg := &Config{
|
| 589 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 590 |
+
"custom": {
|
| 591 |
+
APIKey: "test-key",
|
| 592 |
+
BaseURL: "https://api.custom.com/v1",
|
| 593 |
+
Type: catwalk.TypeOpenAI,
|
| 594 |
+
Models: []catwalk.Model{{
|
| 595 |
+
ID: "test-model",
|
| 596 |
+
}},
|
| 597 |
+
},
|
| 598 |
+
}),
|
| 599 |
+
}
|
| 600 |
+
cfg.setDefaults("/tmp", "")
|
| 601 |
+
|
| 602 |
+
env := env.NewFromMap(map[string]string{})
|
| 603 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 604 |
+
err := cfg.configureProviders(env, resolver, []catwalk.Provider{})
|
| 605 |
+
require.NoError(t, err)
|
| 606 |
+
|
| 607 |
+
require.Equal(t, cfg.Providers.Len(), 1)
|
| 608 |
+
customProvider, exists := cfg.Providers.Get("custom")
|
| 609 |
+
require.True(t, exists)
|
| 610 |
+
require.Equal(t, "custom", customProvider.ID)
|
| 611 |
+
require.Equal(t, "test-key", customProvider.APIKey)
|
| 612 |
+
require.Equal(t, "https://api.custom.com/v1", customProvider.BaseURL)
|
| 613 |
+
})
|
| 614 |
+
|
| 615 |
+
t.Run("custom anthropic provider is supported", func(t *testing.T) {
|
| 616 |
+
cfg := &Config{
|
| 617 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 618 |
+
"custom-anthropic": {
|
| 619 |
+
APIKey: "test-key",
|
| 620 |
+
BaseURL: "https://api.anthropic.com/v1",
|
| 621 |
+
Type: catwalk.TypeAnthropic,
|
| 622 |
+
Models: []catwalk.Model{{
|
| 623 |
+
ID: "claude-3-sonnet",
|
| 624 |
+
}},
|
| 625 |
+
},
|
| 626 |
+
}),
|
| 627 |
+
}
|
| 628 |
+
cfg.setDefaults("/tmp", "")
|
| 629 |
+
|
| 630 |
+
env := env.NewFromMap(map[string]string{})
|
| 631 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 632 |
+
err := cfg.configureProviders(env, resolver, []catwalk.Provider{})
|
| 633 |
+
require.NoError(t, err)
|
| 634 |
+
|
| 635 |
+
require.Equal(t, cfg.Providers.Len(), 1)
|
| 636 |
+
customProvider, exists := cfg.Providers.Get("custom-anthropic")
|
| 637 |
+
require.True(t, exists)
|
| 638 |
+
require.Equal(t, "custom-anthropic", customProvider.ID)
|
| 639 |
+
require.Equal(t, "test-key", customProvider.APIKey)
|
| 640 |
+
require.Equal(t, "https://api.anthropic.com/v1", customProvider.BaseURL)
|
| 641 |
+
require.Equal(t, catwalk.TypeAnthropic, customProvider.Type)
|
| 642 |
+
})
|
| 643 |
+
|
| 644 |
+
t.Run("disabled custom provider is removed", func(t *testing.T) {
|
| 645 |
+
cfg := &Config{
|
| 646 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 647 |
+
"custom": {
|
| 648 |
+
APIKey: "test-key",
|
| 649 |
+
BaseURL: "https://api.custom.com/v1",
|
| 650 |
+
Type: catwalk.TypeOpenAI,
|
| 651 |
+
Disable: true,
|
| 652 |
+
Models: []catwalk.Model{{
|
| 653 |
+
ID: "test-model",
|
| 654 |
+
}},
|
| 655 |
+
},
|
| 656 |
+
}),
|
| 657 |
+
}
|
| 658 |
+
cfg.setDefaults("/tmp", "")
|
| 659 |
+
|
| 660 |
+
env := env.NewFromMap(map[string]string{})
|
| 661 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 662 |
+
err := cfg.configureProviders(env, resolver, []catwalk.Provider{})
|
| 663 |
+
require.NoError(t, err)
|
| 664 |
+
|
| 665 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 666 |
+
_, exists := cfg.Providers.Get("custom")
|
| 667 |
+
require.False(t, exists)
|
| 668 |
+
})
|
| 669 |
+
}
|
| 670 |
+
|
| 671 |
+
func TestConfig_configureProvidersEnhancedCredentialValidation(t *testing.T) {
|
| 672 |
+
t.Run("VertexAI provider removed when credentials missing with existing config", func(t *testing.T) {
|
| 673 |
+
knownProviders := []catwalk.Provider{
|
| 674 |
+
{
|
| 675 |
+
ID: catwalk.InferenceProviderVertexAI,
|
| 676 |
+
APIKey: "",
|
| 677 |
+
APIEndpoint: "",
|
| 678 |
+
Models: []catwalk.Model{{
|
| 679 |
+
ID: "gemini-pro",
|
| 680 |
+
}},
|
| 681 |
+
},
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
cfg := &Config{
|
| 685 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 686 |
+
"vertexai": {
|
| 687 |
+
BaseURL: "custom-url",
|
| 688 |
+
},
|
| 689 |
+
}),
|
| 690 |
+
}
|
| 691 |
+
cfg.setDefaults("/tmp", "")
|
| 692 |
+
|
| 693 |
+
env := env.NewFromMap(map[string]string{
|
| 694 |
+
"GOOGLE_GENAI_USE_VERTEXAI": "false",
|
| 695 |
+
})
|
| 696 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 697 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 698 |
+
require.NoError(t, err)
|
| 699 |
+
|
| 700 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 701 |
+
_, exists := cfg.Providers.Get("vertexai")
|
| 702 |
+
require.False(t, exists)
|
| 703 |
+
})
|
| 704 |
+
|
| 705 |
+
t.Run("Bedrock provider removed when AWS credentials missing with existing config", func(t *testing.T) {
|
| 706 |
+
knownProviders := []catwalk.Provider{
|
| 707 |
+
{
|
| 708 |
+
ID: catwalk.InferenceProviderBedrock,
|
| 709 |
+
APIKey: "",
|
| 710 |
+
APIEndpoint: "",
|
| 711 |
+
Models: []catwalk.Model{{
|
| 712 |
+
ID: "anthropic.claude-sonnet-4-20250514-v1:0",
|
| 713 |
+
}},
|
| 714 |
+
},
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
cfg := &Config{
|
| 718 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 719 |
+
"bedrock": {
|
| 720 |
+
BaseURL: "custom-url",
|
| 721 |
+
},
|
| 722 |
+
}),
|
| 723 |
+
}
|
| 724 |
+
cfg.setDefaults("/tmp", "")
|
| 725 |
+
|
| 726 |
+
env := env.NewFromMap(map[string]string{})
|
| 727 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 728 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 729 |
+
require.NoError(t, err)
|
| 730 |
+
|
| 731 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 732 |
+
_, exists := cfg.Providers.Get("bedrock")
|
| 733 |
+
require.False(t, exists)
|
| 734 |
+
})
|
| 735 |
+
|
| 736 |
+
t.Run("provider removed when API key missing with existing config", func(t *testing.T) {
|
| 737 |
+
knownProviders := []catwalk.Provider{
|
| 738 |
+
{
|
| 739 |
+
ID: "openai",
|
| 740 |
+
APIKey: "$MISSING_API_KEY",
|
| 741 |
+
APIEndpoint: "https://api.openai.com/v1",
|
| 742 |
+
Models: []catwalk.Model{{
|
| 743 |
+
ID: "test-model",
|
| 744 |
+
}},
|
| 745 |
+
},
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
cfg := &Config{
|
| 749 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 750 |
+
"openai": {
|
| 751 |
+
BaseURL: "custom-url",
|
| 752 |
+
},
|
| 753 |
+
}),
|
| 754 |
+
}
|
| 755 |
+
cfg.setDefaults("/tmp", "")
|
| 756 |
+
|
| 757 |
+
env := env.NewFromMap(map[string]string{})
|
| 758 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 759 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 760 |
+
require.NoError(t, err)
|
| 761 |
+
|
| 762 |
+
require.Equal(t, cfg.Providers.Len(), 0)
|
| 763 |
+
_, exists := cfg.Providers.Get("openai")
|
| 764 |
+
require.False(t, exists)
|
| 765 |
+
})
|
| 766 |
+
|
| 767 |
+
t.Run("known provider should still be added if the endpoint is missing the client will use default endpoints", func(t *testing.T) {
|
| 768 |
+
knownProviders := []catwalk.Provider{
|
| 769 |
+
{
|
| 770 |
+
ID: "openai",
|
| 771 |
+
APIKey: "$OPENAI_API_KEY",
|
| 772 |
+
APIEndpoint: "$MISSING_ENDPOINT",
|
| 773 |
+
Models: []catwalk.Model{{
|
| 774 |
+
ID: "test-model",
|
| 775 |
+
}},
|
| 776 |
+
},
|
| 777 |
+
}
|
| 778 |
+
|
| 779 |
+
cfg := &Config{
|
| 780 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 781 |
+
"openai": {
|
| 782 |
+
APIKey: "test-key",
|
| 783 |
+
},
|
| 784 |
+
}),
|
| 785 |
+
}
|
| 786 |
+
cfg.setDefaults("/tmp", "")
|
| 787 |
+
|
| 788 |
+
env := env.NewFromMap(map[string]string{
|
| 789 |
+
"OPENAI_API_KEY": "test-key",
|
| 790 |
+
})
|
| 791 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 792 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 793 |
+
require.NoError(t, err)
|
| 794 |
+
|
| 795 |
+
require.Equal(t, cfg.Providers.Len(), 1)
|
| 796 |
+
_, exists := cfg.Providers.Get("openai")
|
| 797 |
+
require.True(t, exists)
|
| 798 |
+
})
|
| 799 |
+
}
|
| 800 |
+
|
| 801 |
+
func TestConfig_defaultModelSelection(t *testing.T) {
|
| 802 |
+
t.Run("default behavior uses the default models for given provider", func(t *testing.T) {
|
| 803 |
+
knownProviders := []catwalk.Provider{
|
| 804 |
+
{
|
| 805 |
+
ID: "openai",
|
| 806 |
+
APIKey: "abc",
|
| 807 |
+
DefaultLargeModelID: "large-model",
|
| 808 |
+
DefaultSmallModelID: "small-model",
|
| 809 |
+
Models: []catwalk.Model{
|
| 810 |
+
{
|
| 811 |
+
ID: "large-model",
|
| 812 |
+
DefaultMaxTokens: 1000,
|
| 813 |
+
},
|
| 814 |
+
{
|
| 815 |
+
ID: "small-model",
|
| 816 |
+
DefaultMaxTokens: 500,
|
| 817 |
+
},
|
| 818 |
+
},
|
| 819 |
+
},
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
cfg := &Config{}
|
| 823 |
+
cfg.setDefaults("/tmp", "")
|
| 824 |
+
env := env.NewFromMap(map[string]string{})
|
| 825 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 826 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 827 |
+
require.NoError(t, err)
|
| 828 |
+
|
| 829 |
+
large, small, err := cfg.defaultModelSelection(knownProviders)
|
| 830 |
+
require.NoError(t, err)
|
| 831 |
+
require.Equal(t, "large-model", large.Model)
|
| 832 |
+
require.Equal(t, "openai", large.Provider)
|
| 833 |
+
require.Equal(t, int64(1000), large.MaxTokens)
|
| 834 |
+
require.Equal(t, "small-model", small.Model)
|
| 835 |
+
require.Equal(t, "openai", small.Provider)
|
| 836 |
+
require.Equal(t, int64(500), small.MaxTokens)
|
| 837 |
+
})
|
| 838 |
+
t.Run("should error if no providers configured", func(t *testing.T) {
|
| 839 |
+
knownProviders := []catwalk.Provider{
|
| 840 |
+
{
|
| 841 |
+
ID: "openai",
|
| 842 |
+
APIKey: "$MISSING_KEY",
|
| 843 |
+
DefaultLargeModelID: "large-model",
|
| 844 |
+
DefaultSmallModelID: "small-model",
|
| 845 |
+
Models: []catwalk.Model{
|
| 846 |
+
{
|
| 847 |
+
ID: "large-model",
|
| 848 |
+
DefaultMaxTokens: 1000,
|
| 849 |
+
},
|
| 850 |
+
{
|
| 851 |
+
ID: "small-model",
|
| 852 |
+
DefaultMaxTokens: 500,
|
| 853 |
+
},
|
| 854 |
+
},
|
| 855 |
+
},
|
| 856 |
+
}
|
| 857 |
+
|
| 858 |
+
cfg := &Config{}
|
| 859 |
+
cfg.setDefaults("/tmp", "")
|
| 860 |
+
env := env.NewFromMap(map[string]string{})
|
| 861 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 862 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 863 |
+
require.NoError(t, err)
|
| 864 |
+
|
| 865 |
+
_, _, err = cfg.defaultModelSelection(knownProviders)
|
| 866 |
+
require.Error(t, err)
|
| 867 |
+
})
|
| 868 |
+
t.Run("should error if model is missing", func(t *testing.T) {
|
| 869 |
+
knownProviders := []catwalk.Provider{
|
| 870 |
+
{
|
| 871 |
+
ID: "openai",
|
| 872 |
+
APIKey: "abc",
|
| 873 |
+
DefaultLargeModelID: "large-model",
|
| 874 |
+
DefaultSmallModelID: "small-model",
|
| 875 |
+
Models: []catwalk.Model{
|
| 876 |
+
{
|
| 877 |
+
ID: "not-large-model",
|
| 878 |
+
DefaultMaxTokens: 1000,
|
| 879 |
+
},
|
| 880 |
+
{
|
| 881 |
+
ID: "small-model",
|
| 882 |
+
DefaultMaxTokens: 500,
|
| 883 |
+
},
|
| 884 |
+
},
|
| 885 |
+
},
|
| 886 |
+
}
|
| 887 |
+
|
| 888 |
+
cfg := &Config{}
|
| 889 |
+
cfg.setDefaults("/tmp", "")
|
| 890 |
+
env := env.NewFromMap(map[string]string{})
|
| 891 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 892 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 893 |
+
require.NoError(t, err)
|
| 894 |
+
_, _, err = cfg.defaultModelSelection(knownProviders)
|
| 895 |
+
require.Error(t, err)
|
| 896 |
+
})
|
| 897 |
+
|
| 898 |
+
t.Run("should configure the default models with a custom provider", func(t *testing.T) {
|
| 899 |
+
knownProviders := []catwalk.Provider{
|
| 900 |
+
{
|
| 901 |
+
ID: "openai",
|
| 902 |
+
APIKey: "$MISSING", // will not be included in the config
|
| 903 |
+
DefaultLargeModelID: "large-model",
|
| 904 |
+
DefaultSmallModelID: "small-model",
|
| 905 |
+
Models: []catwalk.Model{
|
| 906 |
+
{
|
| 907 |
+
ID: "not-large-model",
|
| 908 |
+
DefaultMaxTokens: 1000,
|
| 909 |
+
},
|
| 910 |
+
{
|
| 911 |
+
ID: "small-model",
|
| 912 |
+
DefaultMaxTokens: 500,
|
| 913 |
+
},
|
| 914 |
+
},
|
| 915 |
+
},
|
| 916 |
+
}
|
| 917 |
+
|
| 918 |
+
cfg := &Config{
|
| 919 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 920 |
+
"custom": {
|
| 921 |
+
APIKey: "test-key",
|
| 922 |
+
BaseURL: "https://api.custom.com/v1",
|
| 923 |
+
Models: []catwalk.Model{
|
| 924 |
+
{
|
| 925 |
+
ID: "model",
|
| 926 |
+
DefaultMaxTokens: 600,
|
| 927 |
+
},
|
| 928 |
+
},
|
| 929 |
+
},
|
| 930 |
+
}),
|
| 931 |
+
}
|
| 932 |
+
cfg.setDefaults("/tmp", "")
|
| 933 |
+
env := env.NewFromMap(map[string]string{})
|
| 934 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 935 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 936 |
+
require.NoError(t, err)
|
| 937 |
+
large, small, err := cfg.defaultModelSelection(knownProviders)
|
| 938 |
+
require.NoError(t, err)
|
| 939 |
+
require.Equal(t, "model", large.Model)
|
| 940 |
+
require.Equal(t, "custom", large.Provider)
|
| 941 |
+
require.Equal(t, int64(600), large.MaxTokens)
|
| 942 |
+
require.Equal(t, "model", small.Model)
|
| 943 |
+
require.Equal(t, "custom", small.Provider)
|
| 944 |
+
require.Equal(t, int64(600), small.MaxTokens)
|
| 945 |
+
})
|
| 946 |
+
|
| 947 |
+
t.Run("should fail if no model configured", func(t *testing.T) {
|
| 948 |
+
knownProviders := []catwalk.Provider{
|
| 949 |
+
{
|
| 950 |
+
ID: "openai",
|
| 951 |
+
APIKey: "$MISSING", // will not be included in the config
|
| 952 |
+
DefaultLargeModelID: "large-model",
|
| 953 |
+
DefaultSmallModelID: "small-model",
|
| 954 |
+
Models: []catwalk.Model{
|
| 955 |
+
{
|
| 956 |
+
ID: "not-large-model",
|
| 957 |
+
DefaultMaxTokens: 1000,
|
| 958 |
+
},
|
| 959 |
+
{
|
| 960 |
+
ID: "small-model",
|
| 961 |
+
DefaultMaxTokens: 500,
|
| 962 |
+
},
|
| 963 |
+
},
|
| 964 |
+
},
|
| 965 |
+
}
|
| 966 |
+
|
| 967 |
+
cfg := &Config{
|
| 968 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 969 |
+
"custom": {
|
| 970 |
+
APIKey: "test-key",
|
| 971 |
+
BaseURL: "https://api.custom.com/v1",
|
| 972 |
+
Models: []catwalk.Model{},
|
| 973 |
+
},
|
| 974 |
+
}),
|
| 975 |
+
}
|
| 976 |
+
cfg.setDefaults("/tmp", "")
|
| 977 |
+
env := env.NewFromMap(map[string]string{})
|
| 978 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 979 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 980 |
+
require.NoError(t, err)
|
| 981 |
+
_, _, err = cfg.defaultModelSelection(knownProviders)
|
| 982 |
+
require.Error(t, err)
|
| 983 |
+
})
|
| 984 |
+
t.Run("should use the default provider first", func(t *testing.T) {
|
| 985 |
+
knownProviders := []catwalk.Provider{
|
| 986 |
+
{
|
| 987 |
+
ID: "openai",
|
| 988 |
+
APIKey: "set",
|
| 989 |
+
DefaultLargeModelID: "large-model",
|
| 990 |
+
DefaultSmallModelID: "small-model",
|
| 991 |
+
Models: []catwalk.Model{
|
| 992 |
+
{
|
| 993 |
+
ID: "large-model",
|
| 994 |
+
DefaultMaxTokens: 1000,
|
| 995 |
+
},
|
| 996 |
+
{
|
| 997 |
+
ID: "small-model",
|
| 998 |
+
DefaultMaxTokens: 500,
|
| 999 |
+
},
|
| 1000 |
+
},
|
| 1001 |
+
},
|
| 1002 |
+
}
|
| 1003 |
+
|
| 1004 |
+
cfg := &Config{
|
| 1005 |
+
Providers: csync.NewMapFrom(map[string]ProviderConfig{
|
| 1006 |
+
"custom": {
|
| 1007 |
+
APIKey: "test-key",
|
| 1008 |
+
BaseURL: "https://api.custom.com/v1",
|
| 1009 |
+
Models: []catwalk.Model{
|
| 1010 |
+
{
|
| 1011 |
+
ID: "large-model",
|
| 1012 |
+
DefaultMaxTokens: 1000,
|
| 1013 |
+
},
|
| 1014 |
+
},
|
| 1015 |
+
},
|
| 1016 |
+
}),
|
| 1017 |
+
}
|
| 1018 |
+
cfg.setDefaults("/tmp", "")
|
| 1019 |
+
env := env.NewFromMap(map[string]string{})
|
| 1020 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 1021 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 1022 |
+
require.NoError(t, err)
|
| 1023 |
+
large, small, err := cfg.defaultModelSelection(knownProviders)
|
| 1024 |
+
require.NoError(t, err)
|
| 1025 |
+
require.Equal(t, "large-model", large.Model)
|
| 1026 |
+
require.Equal(t, "openai", large.Provider)
|
| 1027 |
+
require.Equal(t, int64(1000), large.MaxTokens)
|
| 1028 |
+
require.Equal(t, "small-model", small.Model)
|
| 1029 |
+
require.Equal(t, "openai", small.Provider)
|
| 1030 |
+
require.Equal(t, int64(500), small.MaxTokens)
|
| 1031 |
+
})
|
| 1032 |
+
}
|
| 1033 |
+
|
| 1034 |
+
func TestConfig_configureSelectedModels(t *testing.T) {
|
| 1035 |
+
t.Run("should override defaults", func(t *testing.T) {
|
| 1036 |
+
knownProviders := []catwalk.Provider{
|
| 1037 |
+
{
|
| 1038 |
+
ID: "openai",
|
| 1039 |
+
APIKey: "abc",
|
| 1040 |
+
DefaultLargeModelID: "large-model",
|
| 1041 |
+
DefaultSmallModelID: "small-model",
|
| 1042 |
+
Models: []catwalk.Model{
|
| 1043 |
+
{
|
| 1044 |
+
ID: "larger-model",
|
| 1045 |
+
DefaultMaxTokens: 2000,
|
| 1046 |
+
},
|
| 1047 |
+
{
|
| 1048 |
+
ID: "large-model",
|
| 1049 |
+
DefaultMaxTokens: 1000,
|
| 1050 |
+
},
|
| 1051 |
+
{
|
| 1052 |
+
ID: "small-model",
|
| 1053 |
+
DefaultMaxTokens: 500,
|
| 1054 |
+
},
|
| 1055 |
+
},
|
| 1056 |
+
},
|
| 1057 |
+
}
|
| 1058 |
+
|
| 1059 |
+
cfg := &Config{
|
| 1060 |
+
Models: map[SelectedModelType]SelectedModel{
|
| 1061 |
+
"large": {
|
| 1062 |
+
Model: "larger-model",
|
| 1063 |
+
},
|
| 1064 |
+
},
|
| 1065 |
+
}
|
| 1066 |
+
cfg.setDefaults("/tmp", "")
|
| 1067 |
+
env := env.NewFromMap(map[string]string{})
|
| 1068 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 1069 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 1070 |
+
require.NoError(t, err)
|
| 1071 |
+
|
| 1072 |
+
err = cfg.configureSelectedModels(knownProviders)
|
| 1073 |
+
require.NoError(t, err)
|
| 1074 |
+
large := cfg.Models[SelectedModelTypeLarge]
|
| 1075 |
+
small := cfg.Models[SelectedModelTypeSmall]
|
| 1076 |
+
require.Equal(t, "larger-model", large.Model)
|
| 1077 |
+
require.Equal(t, "openai", large.Provider)
|
| 1078 |
+
require.Equal(t, int64(2000), large.MaxTokens)
|
| 1079 |
+
require.Equal(t, "small-model", small.Model)
|
| 1080 |
+
require.Equal(t, "openai", small.Provider)
|
| 1081 |
+
require.Equal(t, int64(500), small.MaxTokens)
|
| 1082 |
+
})
|
| 1083 |
+
t.Run("should be possible to use multiple providers", func(t *testing.T) {
|
| 1084 |
+
knownProviders := []catwalk.Provider{
|
| 1085 |
+
{
|
| 1086 |
+
ID: "openai",
|
| 1087 |
+
APIKey: "abc",
|
| 1088 |
+
DefaultLargeModelID: "large-model",
|
| 1089 |
+
DefaultSmallModelID: "small-model",
|
| 1090 |
+
Models: []catwalk.Model{
|
| 1091 |
+
{
|
| 1092 |
+
ID: "large-model",
|
| 1093 |
+
DefaultMaxTokens: 1000,
|
| 1094 |
+
},
|
| 1095 |
+
{
|
| 1096 |
+
ID: "small-model",
|
| 1097 |
+
DefaultMaxTokens: 500,
|
| 1098 |
+
},
|
| 1099 |
+
},
|
| 1100 |
+
},
|
| 1101 |
+
{
|
| 1102 |
+
ID: "anthropic",
|
| 1103 |
+
APIKey: "abc",
|
| 1104 |
+
DefaultLargeModelID: "a-large-model",
|
| 1105 |
+
DefaultSmallModelID: "a-small-model",
|
| 1106 |
+
Models: []catwalk.Model{
|
| 1107 |
+
{
|
| 1108 |
+
ID: "a-large-model",
|
| 1109 |
+
DefaultMaxTokens: 1000,
|
| 1110 |
+
},
|
| 1111 |
+
{
|
| 1112 |
+
ID: "a-small-model",
|
| 1113 |
+
DefaultMaxTokens: 200,
|
| 1114 |
+
},
|
| 1115 |
+
},
|
| 1116 |
+
},
|
| 1117 |
+
}
|
| 1118 |
+
|
| 1119 |
+
cfg := &Config{
|
| 1120 |
+
Models: map[SelectedModelType]SelectedModel{
|
| 1121 |
+
"small": {
|
| 1122 |
+
Model: "a-small-model",
|
| 1123 |
+
Provider: "anthropic",
|
| 1124 |
+
MaxTokens: 300,
|
| 1125 |
+
},
|
| 1126 |
+
},
|
| 1127 |
+
}
|
| 1128 |
+
cfg.setDefaults("/tmp", "")
|
| 1129 |
+
env := env.NewFromMap(map[string]string{})
|
| 1130 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 1131 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 1132 |
+
require.NoError(t, err)
|
| 1133 |
+
|
| 1134 |
+
err = cfg.configureSelectedModels(knownProviders)
|
| 1135 |
+
require.NoError(t, err)
|
| 1136 |
+
large := cfg.Models[SelectedModelTypeLarge]
|
| 1137 |
+
small := cfg.Models[SelectedModelTypeSmall]
|
| 1138 |
+
require.Equal(t, "large-model", large.Model)
|
| 1139 |
+
require.Equal(t, "openai", large.Provider)
|
| 1140 |
+
require.Equal(t, int64(1000), large.MaxTokens)
|
| 1141 |
+
require.Equal(t, "a-small-model", small.Model)
|
| 1142 |
+
require.Equal(t, "anthropic", small.Provider)
|
| 1143 |
+
require.Equal(t, int64(300), small.MaxTokens)
|
| 1144 |
+
})
|
| 1145 |
+
|
| 1146 |
+
t.Run("should override the max tokens only", func(t *testing.T) {
|
| 1147 |
+
knownProviders := []catwalk.Provider{
|
| 1148 |
+
{
|
| 1149 |
+
ID: "openai",
|
| 1150 |
+
APIKey: "abc",
|
| 1151 |
+
DefaultLargeModelID: "large-model",
|
| 1152 |
+
DefaultSmallModelID: "small-model",
|
| 1153 |
+
Models: []catwalk.Model{
|
| 1154 |
+
{
|
| 1155 |
+
ID: "large-model",
|
| 1156 |
+
DefaultMaxTokens: 1000,
|
| 1157 |
+
},
|
| 1158 |
+
{
|
| 1159 |
+
ID: "small-model",
|
| 1160 |
+
DefaultMaxTokens: 500,
|
| 1161 |
+
},
|
| 1162 |
+
},
|
| 1163 |
+
},
|
| 1164 |
+
}
|
| 1165 |
+
|
| 1166 |
+
cfg := &Config{
|
| 1167 |
+
Models: map[SelectedModelType]SelectedModel{
|
| 1168 |
+
"large": {
|
| 1169 |
+
MaxTokens: 100,
|
| 1170 |
+
},
|
| 1171 |
+
},
|
| 1172 |
+
}
|
| 1173 |
+
cfg.setDefaults("/tmp", "")
|
| 1174 |
+
env := env.NewFromMap(map[string]string{})
|
| 1175 |
+
resolver := NewEnvironmentVariableResolver(env)
|
| 1176 |
+
err := cfg.configureProviders(env, resolver, knownProviders)
|
| 1177 |
+
require.NoError(t, err)
|
| 1178 |
+
|
| 1179 |
+
err = cfg.configureSelectedModels(knownProviders)
|
| 1180 |
+
require.NoError(t, err)
|
| 1181 |
+
large := cfg.Models[SelectedModelTypeLarge]
|
| 1182 |
+
require.Equal(t, "large-model", large.Model)
|
| 1183 |
+
require.Equal(t, "openai", large.Provider)
|
| 1184 |
+
require.Equal(t, int64(100), large.MaxTokens)
|
| 1185 |
+
})
|
| 1186 |
+
}
|
projects/ui/crush/internal/config/merge.go
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bytes"
|
| 5 |
+
"io"
|
| 6 |
+
|
| 7 |
+
"github.com/qjebbs/go-jsons"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
func Merge(data []io.Reader) (io.Reader, error) {
|
| 11 |
+
got, err := jsons.Merge(data)
|
| 12 |
+
if err != nil {
|
| 13 |
+
return nil, err
|
| 14 |
+
}
|
| 15 |
+
return bytes.NewReader(got), nil
|
| 16 |
+
}
|
projects/ui/crush/internal/config/merge_test.go
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"io"
|
| 5 |
+
"strings"
|
| 6 |
+
"testing"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
func TestMerge(t *testing.T) {
|
| 10 |
+
data1 := strings.NewReader(`{"foo": "bar"}`)
|
| 11 |
+
data2 := strings.NewReader(`{"baz": "qux"}`)
|
| 12 |
+
|
| 13 |
+
merged, err := Merge([]io.Reader{data1, data2})
|
| 14 |
+
if err != nil {
|
| 15 |
+
t.Fatalf("expected no error, got %v", err)
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
expected := `{"baz":"qux","foo":"bar"}`
|
| 19 |
+
got, err := io.ReadAll(merged)
|
| 20 |
+
if err != nil {
|
| 21 |
+
t.Fatalf("expected no error reading merged data, got %v", err)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
if string(got) != expected {
|
| 25 |
+
t.Errorf("expected %s, got %s", expected, string(got))
|
| 26 |
+
}
|
| 27 |
+
}
|
projects/ui/crush/internal/config/provider.go
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"cmp"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"fmt"
|
| 7 |
+
"log/slog"
|
| 8 |
+
"os"
|
| 9 |
+
"path/filepath"
|
| 10 |
+
"runtime"
|
| 11 |
+
"sync"
|
| 12 |
+
"time"
|
| 13 |
+
|
| 14 |
+
"github.com/charmbracelet/catwalk/pkg/catwalk"
|
| 15 |
+
"github.com/charmbracelet/crush/internal/home"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
type ProviderClient interface {
|
| 19 |
+
GetProviders() ([]catwalk.Provider, error)
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
var (
|
| 23 |
+
providerOnce sync.Once
|
| 24 |
+
providerList []catwalk.Provider
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
// file to cache provider data
|
| 28 |
+
func providerCacheFileData() string {
|
| 29 |
+
xdgDataHome := os.Getenv("XDG_DATA_HOME")
|
| 30 |
+
if xdgDataHome != "" {
|
| 31 |
+
return filepath.Join(xdgDataHome, appName, "providers.json")
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
// return the path to the main data directory
|
| 35 |
+
// for windows, it should be in `%LOCALAPPDATA%/crush/`
|
| 36 |
+
// for linux and macOS, it should be in `$HOME/.local/share/crush/`
|
| 37 |
+
if runtime.GOOS == "windows" {
|
| 38 |
+
localAppData := os.Getenv("LOCALAPPDATA")
|
| 39 |
+
if localAppData == "" {
|
| 40 |
+
localAppData = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
|
| 41 |
+
}
|
| 42 |
+
return filepath.Join(localAppData, appName, "providers.json")
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
return filepath.Join(home.Dir(), ".local", "share", appName, "providers.json")
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
func saveProvidersInCache(path string, providers []catwalk.Provider) error {
|
| 49 |
+
slog.Info("Saving cached provider data", "path", path)
|
| 50 |
+
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
| 51 |
+
return fmt.Errorf("failed to create directory for provider cache: %w", err)
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
data, err := json.MarshalIndent(providers, "", " ")
|
| 55 |
+
if err != nil {
|
| 56 |
+
return fmt.Errorf("failed to marshal provider data: %w", err)
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
if err := os.WriteFile(path, data, 0o644); err != nil {
|
| 60 |
+
return fmt.Errorf("failed to write provider data to cache: %w", err)
|
| 61 |
+
}
|
| 62 |
+
return nil
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
func loadProvidersFromCache(path string) ([]catwalk.Provider, error) {
|
| 66 |
+
data, err := os.ReadFile(path)
|
| 67 |
+
if err != nil {
|
| 68 |
+
return nil, fmt.Errorf("failed to read provider cache file: %w", err)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
var providers []catwalk.Provider
|
| 72 |
+
if err := json.Unmarshal(data, &providers); err != nil {
|
| 73 |
+
return nil, fmt.Errorf("failed to unmarshal provider data from cache: %w", err)
|
| 74 |
+
}
|
| 75 |
+
return providers, nil
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
func Providers() ([]catwalk.Provider, error) {
|
| 79 |
+
catwalkURL := cmp.Or(os.Getenv("CATWALK_URL"), defaultCatwalkURL)
|
| 80 |
+
client := catwalk.NewWithURL(catwalkURL)
|
| 81 |
+
path := providerCacheFileData()
|
| 82 |
+
return loadProvidersOnce(client, path)
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
func loadProvidersOnce(client ProviderClient, path string) ([]catwalk.Provider, error) {
|
| 86 |
+
var err error
|
| 87 |
+
providerOnce.Do(func() {
|
| 88 |
+
providerList, err = loadProviders(client, path)
|
| 89 |
+
})
|
| 90 |
+
if err != nil {
|
| 91 |
+
return nil, err
|
| 92 |
+
}
|
| 93 |
+
return providerList, nil
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
func loadProviders(client ProviderClient, path string) (providerList []catwalk.Provider, err error) {
|
| 97 |
+
// if cache is not stale, load from it
|
| 98 |
+
stale, exists := isCacheStale(path)
|
| 99 |
+
if !stale {
|
| 100 |
+
slog.Info("Using cached provider data", "path", path)
|
| 101 |
+
providerList, err = loadProvidersFromCache(path)
|
| 102 |
+
if len(providerList) > 0 && err == nil {
|
| 103 |
+
go func() {
|
| 104 |
+
slog.Info("Updating provider cache in background", "path", path)
|
| 105 |
+
updated, uerr := client.GetProviders()
|
| 106 |
+
if len(updated) > 0 && uerr == nil {
|
| 107 |
+
_ = saveProvidersInCache(path, updated)
|
| 108 |
+
}
|
| 109 |
+
}()
|
| 110 |
+
return
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
slog.Info("Getting live provider data", "path", path)
|
| 115 |
+
providerList, err = client.GetProviders()
|
| 116 |
+
if len(providerList) > 0 && err == nil {
|
| 117 |
+
err = saveProvidersInCache(path, providerList)
|
| 118 |
+
return
|
| 119 |
+
}
|
| 120 |
+
if !exists {
|
| 121 |
+
err = fmt.Errorf("failed to load providers")
|
| 122 |
+
return
|
| 123 |
+
}
|
| 124 |
+
slog.Info("Loading provider data from cache", "path", path)
|
| 125 |
+
providerList, err = loadProvidersFromCache(path)
|
| 126 |
+
return
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
func isCacheStale(path string) (stale, exists bool) {
|
| 130 |
+
info, err := os.Stat(path)
|
| 131 |
+
if err != nil {
|
| 132 |
+
return true, false
|
| 133 |
+
}
|
| 134 |
+
return time.Since(info.ModTime()) > 24*time.Hour, true
|
| 135 |
+
}
|
projects/ui/crush/internal/config/provider_empty_test.go
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"os"
|
| 6 |
+
"testing"
|
| 7 |
+
|
| 8 |
+
"github.com/charmbracelet/catwalk/pkg/catwalk"
|
| 9 |
+
"github.com/stretchr/testify/require"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
type emptyProviderClient struct{}
|
| 13 |
+
|
| 14 |
+
func (m *emptyProviderClient) GetProviders() ([]catwalk.Provider, error) {
|
| 15 |
+
return []catwalk.Provider{}, nil
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
func TestProvider_loadProvidersEmptyResult(t *testing.T) {
|
| 19 |
+
client := &emptyProviderClient{}
|
| 20 |
+
tmpPath := t.TempDir() + "/providers.json"
|
| 21 |
+
|
| 22 |
+
providers, err := loadProviders(client, tmpPath)
|
| 23 |
+
require.EqualError(t, err, "failed to load providers")
|
| 24 |
+
require.Empty(t, providers)
|
| 25 |
+
require.Len(t, providers, 0)
|
| 26 |
+
|
| 27 |
+
// Check that no cache file was created for empty results
|
| 28 |
+
require.NoFileExists(t, tmpPath, "Cache file should not exist for empty results")
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
func TestProvider_loadProvidersEmptyCache(t *testing.T) {
|
| 32 |
+
client := &mockProviderClient{shouldFail: false}
|
| 33 |
+
tmpPath := t.TempDir() + "/providers.json"
|
| 34 |
+
|
| 35 |
+
// Create an empty cache file
|
| 36 |
+
emptyProviders := []catwalk.Provider{}
|
| 37 |
+
data, err := json.Marshal(emptyProviders)
|
| 38 |
+
require.NoError(t, err)
|
| 39 |
+
require.NoError(t, os.WriteFile(tmpPath, data, 0o644))
|
| 40 |
+
|
| 41 |
+
// Should refresh and get real providers instead of using empty cache
|
| 42 |
+
providers, err := loadProviders(client, tmpPath)
|
| 43 |
+
require.NoError(t, err)
|
| 44 |
+
require.NotNil(t, providers)
|
| 45 |
+
require.Len(t, providers, 1)
|
| 46 |
+
require.Equal(t, "Mock", providers[0].Name)
|
| 47 |
+
}
|
projects/ui/crush/internal/config/provider_test.go
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"errors"
|
| 6 |
+
"os"
|
| 7 |
+
"testing"
|
| 8 |
+
|
| 9 |
+
"github.com/charmbracelet/catwalk/pkg/catwalk"
|
| 10 |
+
"github.com/stretchr/testify/require"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
type mockProviderClient struct {
|
| 14 |
+
shouldFail bool
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
func (m *mockProviderClient) GetProviders() ([]catwalk.Provider, error) {
|
| 18 |
+
if m.shouldFail {
|
| 19 |
+
return nil, errors.New("failed to load providers")
|
| 20 |
+
}
|
| 21 |
+
return []catwalk.Provider{
|
| 22 |
+
{
|
| 23 |
+
Name: "Mock",
|
| 24 |
+
},
|
| 25 |
+
}, nil
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func TestProvider_loadProvidersNoIssues(t *testing.T) {
|
| 29 |
+
client := &mockProviderClient{shouldFail: false}
|
| 30 |
+
tmpPath := t.TempDir() + "/providers.json"
|
| 31 |
+
providers, err := loadProviders(client, tmpPath)
|
| 32 |
+
require.NoError(t, err)
|
| 33 |
+
require.NotNil(t, providers)
|
| 34 |
+
require.Len(t, providers, 1)
|
| 35 |
+
|
| 36 |
+
// check if file got saved
|
| 37 |
+
fileInfo, err := os.Stat(tmpPath)
|
| 38 |
+
require.NoError(t, err)
|
| 39 |
+
require.False(t, fileInfo.IsDir(), "Expected a file, not a directory")
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
func TestProvider_loadProvidersWithIssues(t *testing.T) {
|
| 43 |
+
client := &mockProviderClient{shouldFail: true}
|
| 44 |
+
tmpPath := t.TempDir() + "/providers.json"
|
| 45 |
+
// store providers to a temporary file
|
| 46 |
+
oldProviders := []catwalk.Provider{
|
| 47 |
+
{
|
| 48 |
+
Name: "OldProvider",
|
| 49 |
+
},
|
| 50 |
+
}
|
| 51 |
+
data, err := json.Marshal(oldProviders)
|
| 52 |
+
if err != nil {
|
| 53 |
+
t.Fatalf("Failed to marshal old providers: %v", err)
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
err = os.WriteFile(tmpPath, data, 0o644)
|
| 57 |
+
if err != nil {
|
| 58 |
+
t.Fatalf("Failed to write old providers to file: %v", err)
|
| 59 |
+
}
|
| 60 |
+
providers, err := loadProviders(client, tmpPath)
|
| 61 |
+
require.NoError(t, err)
|
| 62 |
+
require.NotNil(t, providers)
|
| 63 |
+
require.Len(t, providers, 1)
|
| 64 |
+
require.Equal(t, "OldProvider", providers[0].Name, "Expected to keep old provider when loading fails")
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
func TestProvider_loadProvidersWithIssuesAndNoCache(t *testing.T) {
|
| 68 |
+
client := &mockProviderClient{shouldFail: true}
|
| 69 |
+
tmpPath := t.TempDir() + "/providers.json"
|
| 70 |
+
providers, err := loadProviders(client, tmpPath)
|
| 71 |
+
require.Error(t, err)
|
| 72 |
+
require.Nil(t, providers, "Expected nil providers when loading fails and no cache exists")
|
| 73 |
+
}
|
projects/ui/crush/internal/config/resolve.go
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"fmt"
|
| 6 |
+
"strings"
|
| 7 |
+
"time"
|
| 8 |
+
|
| 9 |
+
"github.com/charmbracelet/crush/internal/env"
|
| 10 |
+
"github.com/charmbracelet/crush/internal/shell"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
type VariableResolver interface {
|
| 14 |
+
ResolveValue(value string) (string, error)
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
type Shell interface {
|
| 18 |
+
Exec(ctx context.Context, command string) (stdout, stderr string, err error)
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
type shellVariableResolver struct {
|
| 22 |
+
shell Shell
|
| 23 |
+
env env.Env
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
func NewShellVariableResolver(env env.Env) VariableResolver {
|
| 27 |
+
return &shellVariableResolver{
|
| 28 |
+
env: env,
|
| 29 |
+
shell: shell.NewShell(
|
| 30 |
+
&shell.Options{
|
| 31 |
+
Env: env.Env(),
|
| 32 |
+
},
|
| 33 |
+
),
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// ResolveValue is a method for resolving values, such as environment variables.
|
| 38 |
+
// it will resolve shell-like variable substitution anywhere in the string, including:
|
| 39 |
+
// - $(command) for command substitution
|
| 40 |
+
// - $VAR or ${VAR} for environment variables
|
| 41 |
+
func (r *shellVariableResolver) ResolveValue(value string) (string, error) {
|
| 42 |
+
// Special case: lone $ is an error (backward compatibility)
|
| 43 |
+
if value == "$" {
|
| 44 |
+
return "", fmt.Errorf("invalid value format: %s", value)
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// If no $ found, return as-is
|
| 48 |
+
if !strings.Contains(value, "$") {
|
| 49 |
+
return value, nil
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
result := value
|
| 53 |
+
|
| 54 |
+
// Handle command substitution: $(command)
|
| 55 |
+
for {
|
| 56 |
+
start := strings.Index(result, "$(")
|
| 57 |
+
if start == -1 {
|
| 58 |
+
break
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// Find matching closing parenthesis
|
| 62 |
+
depth := 0
|
| 63 |
+
end := -1
|
| 64 |
+
for i := start + 2; i < len(result); i++ {
|
| 65 |
+
if result[i] == '(' {
|
| 66 |
+
depth++
|
| 67 |
+
} else if result[i] == ')' {
|
| 68 |
+
if depth == 0 {
|
| 69 |
+
end = i
|
| 70 |
+
break
|
| 71 |
+
}
|
| 72 |
+
depth--
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
if end == -1 {
|
| 77 |
+
return "", fmt.Errorf("unmatched $( in value: %s", value)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
command := result[start+2 : end]
|
| 81 |
+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
| 82 |
+
|
| 83 |
+
stdout, _, err := r.shell.Exec(ctx, command)
|
| 84 |
+
cancel()
|
| 85 |
+
if err != nil {
|
| 86 |
+
return "", fmt.Errorf("command execution failed for '%s': %w", command, err)
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
// Replace the $(command) with the output
|
| 90 |
+
replacement := strings.TrimSpace(stdout)
|
| 91 |
+
result = result[:start] + replacement + result[end+1:]
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// Handle environment variables: $VAR and ${VAR}
|
| 95 |
+
searchStart := 0
|
| 96 |
+
for {
|
| 97 |
+
start := strings.Index(result[searchStart:], "$")
|
| 98 |
+
if start == -1 {
|
| 99 |
+
break
|
| 100 |
+
}
|
| 101 |
+
start += searchStart // Adjust for the offset
|
| 102 |
+
|
| 103 |
+
// Skip if this is part of $( which we already handled
|
| 104 |
+
if start+1 < len(result) && result[start+1] == '(' {
|
| 105 |
+
// Skip past this $(...)
|
| 106 |
+
searchStart = start + 1
|
| 107 |
+
continue
|
| 108 |
+
}
|
| 109 |
+
var varName string
|
| 110 |
+
var end int
|
| 111 |
+
|
| 112 |
+
if start+1 < len(result) && result[start+1] == '{' {
|
| 113 |
+
// Handle ${VAR} format
|
| 114 |
+
closeIdx := strings.Index(result[start+2:], "}")
|
| 115 |
+
if closeIdx == -1 {
|
| 116 |
+
return "", fmt.Errorf("unmatched ${ in value: %s", value)
|
| 117 |
+
}
|
| 118 |
+
varName = result[start+2 : start+2+closeIdx]
|
| 119 |
+
end = start + 2 + closeIdx + 1
|
| 120 |
+
} else {
|
| 121 |
+
// Handle $VAR format - variable names must start with letter or underscore
|
| 122 |
+
if start+1 >= len(result) {
|
| 123 |
+
return "", fmt.Errorf("incomplete variable reference at end of string: %s", value)
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
if result[start+1] != '_' &&
|
| 127 |
+
(result[start+1] < 'a' || result[start+1] > 'z') &&
|
| 128 |
+
(result[start+1] < 'A' || result[start+1] > 'Z') {
|
| 129 |
+
return "", fmt.Errorf("invalid variable name starting with '%c' in: %s", result[start+1], value)
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
end = start + 1
|
| 133 |
+
for end < len(result) && (result[end] == '_' ||
|
| 134 |
+
(result[end] >= 'a' && result[end] <= 'z') ||
|
| 135 |
+
(result[end] >= 'A' && result[end] <= 'Z') ||
|
| 136 |
+
(result[end] >= '0' && result[end] <= '9')) {
|
| 137 |
+
end++
|
| 138 |
+
}
|
| 139 |
+
varName = result[start+1 : end]
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
envValue := r.env.Get(varName)
|
| 143 |
+
if envValue == "" {
|
| 144 |
+
return "", fmt.Errorf("environment variable %q not set", varName)
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
result = result[:start] + envValue + result[end:]
|
| 148 |
+
searchStart = start + len(envValue) // Continue searching after the replacement
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
return result, nil
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
type environmentVariableResolver struct {
|
| 155 |
+
env env.Env
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
func NewEnvironmentVariableResolver(env env.Env) VariableResolver {
|
| 159 |
+
return &environmentVariableResolver{
|
| 160 |
+
env: env,
|
| 161 |
+
}
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
// ResolveValue resolves environment variables from the provided env.Env.
|
| 165 |
+
func (r *environmentVariableResolver) ResolveValue(value string) (string, error) {
|
| 166 |
+
if !strings.HasPrefix(value, "$") {
|
| 167 |
+
return value, nil
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
varName := strings.TrimPrefix(value, "$")
|
| 171 |
+
resolvedValue := r.env.Get(varName)
|
| 172 |
+
if resolvedValue == "" {
|
| 173 |
+
return "", fmt.Errorf("environment variable %q not set", varName)
|
| 174 |
+
}
|
| 175 |
+
return resolvedValue, nil
|
| 176 |
+
}
|
projects/ui/crush/internal/config/resolve_test.go
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package config
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"errors"
|
| 6 |
+
"testing"
|
| 7 |
+
|
| 8 |
+
"github.com/charmbracelet/crush/internal/env"
|
| 9 |
+
"github.com/stretchr/testify/require"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// mockShell implements the Shell interface for testing
|
| 13 |
+
type mockShell struct {
|
| 14 |
+
execFunc func(ctx context.Context, command string) (stdout, stderr string, err error)
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
func (m *mockShell) Exec(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 18 |
+
if m.execFunc != nil {
|
| 19 |
+
return m.execFunc(ctx, command)
|
| 20 |
+
}
|
| 21 |
+
return "", "", nil
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func TestShellVariableResolver_ResolveValue(t *testing.T) {
|
| 25 |
+
tests := []struct {
|
| 26 |
+
name string
|
| 27 |
+
value string
|
| 28 |
+
envVars map[string]string
|
| 29 |
+
shellFunc func(ctx context.Context, command string) (stdout, stderr string, err error)
|
| 30 |
+
expected string
|
| 31 |
+
expectError bool
|
| 32 |
+
}{
|
| 33 |
+
{
|
| 34 |
+
name: "non-variable string returns as-is",
|
| 35 |
+
value: "plain-string",
|
| 36 |
+
expected: "plain-string",
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
name: "environment variable resolution",
|
| 40 |
+
value: "$HOME",
|
| 41 |
+
envVars: map[string]string{"HOME": "/home/user"},
|
| 42 |
+
expected: "/home/user",
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
name: "missing environment variable returns error",
|
| 46 |
+
value: "$MISSING_VAR",
|
| 47 |
+
envVars: map[string]string{},
|
| 48 |
+
expectError: true,
|
| 49 |
+
},
|
| 50 |
+
|
| 51 |
+
{
|
| 52 |
+
name: "shell command with whitespace trimming",
|
| 53 |
+
value: "$(echo ' spaced ')",
|
| 54 |
+
shellFunc: func(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 55 |
+
if command == "echo ' spaced '" {
|
| 56 |
+
return " spaced \n", "", nil
|
| 57 |
+
}
|
| 58 |
+
return "", "", errors.New("unexpected command")
|
| 59 |
+
},
|
| 60 |
+
expected: "spaced",
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
name: "shell command execution error",
|
| 64 |
+
value: "$(false)",
|
| 65 |
+
shellFunc: func(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 66 |
+
return "", "", errors.New("command failed")
|
| 67 |
+
},
|
| 68 |
+
expectError: true,
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
name: "invalid format returns error",
|
| 72 |
+
value: "$",
|
| 73 |
+
expectError: true,
|
| 74 |
+
},
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
for _, tt := range tests {
|
| 78 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 79 |
+
testEnv := env.NewFromMap(tt.envVars)
|
| 80 |
+
resolver := &shellVariableResolver{
|
| 81 |
+
shell: &mockShell{execFunc: tt.shellFunc},
|
| 82 |
+
env: testEnv,
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
result, err := resolver.ResolveValue(tt.value)
|
| 86 |
+
|
| 87 |
+
if tt.expectError {
|
| 88 |
+
require.Error(t, err)
|
| 89 |
+
} else {
|
| 90 |
+
require.NoError(t, err)
|
| 91 |
+
require.Equal(t, tt.expected, result)
|
| 92 |
+
}
|
| 93 |
+
})
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
func TestShellVariableResolver_EnhancedResolveValue(t *testing.T) {
|
| 98 |
+
tests := []struct {
|
| 99 |
+
name string
|
| 100 |
+
value string
|
| 101 |
+
envVars map[string]string
|
| 102 |
+
shellFunc func(ctx context.Context, command string) (stdout, stderr string, err error)
|
| 103 |
+
expected string
|
| 104 |
+
expectError bool
|
| 105 |
+
}{
|
| 106 |
+
{
|
| 107 |
+
name: "command substitution within string",
|
| 108 |
+
value: "Bearer $(echo token123)",
|
| 109 |
+
shellFunc: func(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 110 |
+
if command == "echo token123" {
|
| 111 |
+
return "token123\n", "", nil
|
| 112 |
+
}
|
| 113 |
+
return "", "", errors.New("unexpected command")
|
| 114 |
+
},
|
| 115 |
+
expected: "Bearer token123",
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
name: "environment variable within string",
|
| 119 |
+
value: "Bearer $TOKEN",
|
| 120 |
+
envVars: map[string]string{"TOKEN": "sk-ant-123"},
|
| 121 |
+
expected: "Bearer sk-ant-123",
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
name: "environment variable with braces within string",
|
| 125 |
+
value: "Bearer ${TOKEN}",
|
| 126 |
+
envVars: map[string]string{"TOKEN": "sk-ant-456"},
|
| 127 |
+
expected: "Bearer sk-ant-456",
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
name: "mixed command and environment substitution",
|
| 131 |
+
value: "$USER-$(date +%Y)-$HOST",
|
| 132 |
+
envVars: map[string]string{
|
| 133 |
+
"USER": "testuser",
|
| 134 |
+
"HOST": "localhost",
|
| 135 |
+
},
|
| 136 |
+
shellFunc: func(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 137 |
+
if command == "date +%Y" {
|
| 138 |
+
return "2024\n", "", nil
|
| 139 |
+
}
|
| 140 |
+
return "", "", errors.New("unexpected command")
|
| 141 |
+
},
|
| 142 |
+
expected: "testuser-2024-localhost",
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
name: "multiple command substitutions",
|
| 146 |
+
value: "$(echo hello) $(echo world)",
|
| 147 |
+
shellFunc: func(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 148 |
+
switch command {
|
| 149 |
+
case "echo hello":
|
| 150 |
+
return "hello\n", "", nil
|
| 151 |
+
case "echo world":
|
| 152 |
+
return "world\n", "", nil
|
| 153 |
+
}
|
| 154 |
+
return "", "", errors.New("unexpected command")
|
| 155 |
+
},
|
| 156 |
+
expected: "hello world",
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
name: "nested parentheses in command",
|
| 160 |
+
value: "$(echo $(echo inner))",
|
| 161 |
+
shellFunc: func(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 162 |
+
if command == "echo $(echo inner)" {
|
| 163 |
+
return "nested\n", "", nil
|
| 164 |
+
}
|
| 165 |
+
return "", "", errors.New("unexpected command")
|
| 166 |
+
},
|
| 167 |
+
expected: "nested",
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
name: "lone dollar with non-variable chars",
|
| 171 |
+
value: "prefix$123suffix", // Numbers can't start variable names
|
| 172 |
+
expectError: true,
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
name: "dollar with special chars",
|
| 176 |
+
value: "a$@b$#c", // Special chars aren't valid in variable names
|
| 177 |
+
expectError: true,
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
name: "empty environment variable substitution",
|
| 181 |
+
value: "Bearer $EMPTY_VAR",
|
| 182 |
+
envVars: map[string]string{},
|
| 183 |
+
expectError: true,
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
name: "unmatched command substitution opening",
|
| 187 |
+
value: "Bearer $(echo test",
|
| 188 |
+
expectError: true,
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
name: "unmatched environment variable braces",
|
| 192 |
+
value: "Bearer ${TOKEN",
|
| 193 |
+
expectError: true,
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
name: "command substitution with error",
|
| 197 |
+
value: "Bearer $(false)",
|
| 198 |
+
shellFunc: func(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 199 |
+
return "", "", errors.New("command failed")
|
| 200 |
+
},
|
| 201 |
+
expectError: true,
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
name: "complex real-world example",
|
| 205 |
+
value: "Bearer $(cat /tmp/token.txt | base64 -w 0)",
|
| 206 |
+
shellFunc: func(ctx context.Context, command string) (stdout, stderr string, err error) {
|
| 207 |
+
if command == "cat /tmp/token.txt | base64 -w 0" {
|
| 208 |
+
return "c2stYW50LXRlc3Q=\n", "", nil
|
| 209 |
+
}
|
| 210 |
+
return "", "", errors.New("unexpected command")
|
| 211 |
+
},
|
| 212 |
+
expected: "Bearer c2stYW50LXRlc3Q=",
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
name: "environment variable with underscores and numbers",
|
| 216 |
+
value: "Bearer $API_KEY_V2",
|
| 217 |
+
envVars: map[string]string{"API_KEY_V2": "sk-test-123"},
|
| 218 |
+
expected: "Bearer sk-test-123",
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
name: "no substitution needed",
|
| 222 |
+
value: "Bearer sk-ant-static-token",
|
| 223 |
+
expected: "Bearer sk-ant-static-token",
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
name: "incomplete variable at end",
|
| 227 |
+
value: "Bearer $",
|
| 228 |
+
expectError: true,
|
| 229 |
+
},
|
| 230 |
+
{
|
| 231 |
+
name: "variable with invalid character",
|
| 232 |
+
value: "Bearer $VAR-NAME", // Hyphen not allowed in variable names
|
| 233 |
+
expectError: true,
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
name: "multiple invalid variables",
|
| 237 |
+
value: "$1$2$3",
|
| 238 |
+
expectError: true,
|
| 239 |
+
},
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
for _, tt := range tests {
|
| 243 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 244 |
+
testEnv := env.NewFromMap(tt.envVars)
|
| 245 |
+
resolver := &shellVariableResolver{
|
| 246 |
+
shell: &mockShell{execFunc: tt.shellFunc},
|
| 247 |
+
env: testEnv,
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
result, err := resolver.ResolveValue(tt.value)
|
| 251 |
+
|
| 252 |
+
if tt.expectError {
|
| 253 |
+
require.Error(t, err)
|
| 254 |
+
} else {
|
| 255 |
+
require.NoError(t, err)
|
| 256 |
+
require.Equal(t, tt.expected, result)
|
| 257 |
+
}
|
| 258 |
+
})
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
func TestEnvironmentVariableResolver_ResolveValue(t *testing.T) {
|
| 263 |
+
tests := []struct {
|
| 264 |
+
name string
|
| 265 |
+
value string
|
| 266 |
+
envVars map[string]string
|
| 267 |
+
expected string
|
| 268 |
+
expectError bool
|
| 269 |
+
}{
|
| 270 |
+
{
|
| 271 |
+
name: "non-variable string returns as-is",
|
| 272 |
+
value: "plain-string",
|
| 273 |
+
expected: "plain-string",
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
name: "environment variable resolution",
|
| 277 |
+
value: "$HOME",
|
| 278 |
+
envVars: map[string]string{"HOME": "/home/user"},
|
| 279 |
+
expected: "/home/user",
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
name: "environment variable with complex value",
|
| 283 |
+
value: "$PATH",
|
| 284 |
+
envVars: map[string]string{"PATH": "/usr/bin:/bin:/usr/local/bin"},
|
| 285 |
+
expected: "/usr/bin:/bin:/usr/local/bin",
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
name: "missing environment variable returns error",
|
| 289 |
+
value: "$MISSING_VAR",
|
| 290 |
+
envVars: map[string]string{},
|
| 291 |
+
expectError: true,
|
| 292 |
+
},
|
| 293 |
+
{
|
| 294 |
+
name: "empty environment variable returns error",
|
| 295 |
+
value: "$EMPTY_VAR",
|
| 296 |
+
envVars: map[string]string{"EMPTY_VAR": ""},
|
| 297 |
+
expectError: true,
|
| 298 |
+
},
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
for _, tt := range tests {
|
| 302 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 303 |
+
testEnv := env.NewFromMap(tt.envVars)
|
| 304 |
+
resolver := NewEnvironmentVariableResolver(testEnv)
|
| 305 |
+
|
| 306 |
+
result, err := resolver.ResolveValue(tt.value)
|
| 307 |
+
|
| 308 |
+
if tt.expectError {
|
| 309 |
+
require.Error(t, err)
|
| 310 |
+
} else {
|
| 311 |
+
require.NoError(t, err)
|
| 312 |
+
require.Equal(t, tt.expected, result)
|
| 313 |
+
}
|
| 314 |
+
})
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
func TestNewShellVariableResolver(t *testing.T) {
|
| 319 |
+
testEnv := env.NewFromMap(map[string]string{"TEST": "value"})
|
| 320 |
+
resolver := NewShellVariableResolver(testEnv)
|
| 321 |
+
|
| 322 |
+
require.NotNil(t, resolver)
|
| 323 |
+
require.Implements(t, (*VariableResolver)(nil), resolver)
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
func TestNewEnvironmentVariableResolver(t *testing.T) {
|
| 327 |
+
testEnv := env.NewFromMap(map[string]string{"TEST": "value"})
|
| 328 |
+
resolver := NewEnvironmentVariableResolver(testEnv)
|
| 329 |
+
|
| 330 |
+
require.NotNil(t, resolver)
|
| 331 |
+
require.Implements(t, (*VariableResolver)(nil), resolver)
|
| 332 |
+
}
|
projects/ui/crush/internal/csync/doc.go
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package csync provides concurrent data structures for safe access in
|
| 2 |
+
// multi-threaded environments.
|
| 3 |
+
package csync
|
projects/ui/crush/internal/csync/maps.go
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package csync
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"iter"
|
| 6 |
+
"maps"
|
| 7 |
+
"sync"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
// Map is a concurrent map implementation that provides thread-safe access.
|
| 11 |
+
type Map[K comparable, V any] struct {
|
| 12 |
+
inner map[K]V
|
| 13 |
+
mu sync.RWMutex
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
// NewMap creates a new thread-safe map with the specified key and value types.
|
| 17 |
+
func NewMap[K comparable, V any]() *Map[K, V] {
|
| 18 |
+
return &Map[K, V]{
|
| 19 |
+
inner: make(map[K]V),
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// NewMapFrom creates a new thread-safe map from an existing map.
|
| 24 |
+
func NewMapFrom[K comparable, V any](m map[K]V) *Map[K, V] {
|
| 25 |
+
return &Map[K, V]{
|
| 26 |
+
inner: m,
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// Set sets the value for the specified key in the map.
|
| 31 |
+
func (m *Map[K, V]) Set(key K, value V) {
|
| 32 |
+
m.mu.Lock()
|
| 33 |
+
defer m.mu.Unlock()
|
| 34 |
+
m.inner[key] = value
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// Del deletes the specified key from the map.
|
| 38 |
+
func (m *Map[K, V]) Del(key K) {
|
| 39 |
+
m.mu.Lock()
|
| 40 |
+
defer m.mu.Unlock()
|
| 41 |
+
delete(m.inner, key)
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
// Get gets the value for the specified key from the map.
|
| 45 |
+
func (m *Map[K, V]) Get(key K) (V, bool) {
|
| 46 |
+
m.mu.RLock()
|
| 47 |
+
defer m.mu.RUnlock()
|
| 48 |
+
v, ok := m.inner[key]
|
| 49 |
+
return v, ok
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
// Len returns the number of items in the map.
|
| 53 |
+
func (m *Map[K, V]) Len() int {
|
| 54 |
+
m.mu.RLock()
|
| 55 |
+
defer m.mu.RUnlock()
|
| 56 |
+
return len(m.inner)
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// GetOrSet gets and returns the key if it exists, otherwise, it executes the
|
| 60 |
+
// given function, set its return value for the given key, and returns it.
|
| 61 |
+
func (m *Map[K, V]) GetOrSet(key K, fn func() V) V {
|
| 62 |
+
got, ok := m.Get(key)
|
| 63 |
+
if ok {
|
| 64 |
+
return got
|
| 65 |
+
}
|
| 66 |
+
value := fn()
|
| 67 |
+
m.Set(key, value)
|
| 68 |
+
return value
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// Take gets an item and then deletes it.
|
| 72 |
+
func (m *Map[K, V]) Take(key K) (V, bool) {
|
| 73 |
+
m.mu.Lock()
|
| 74 |
+
defer m.mu.Unlock()
|
| 75 |
+
v, ok := m.inner[key]
|
| 76 |
+
delete(m.inner, key)
|
| 77 |
+
return v, ok
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
// Seq2 returns an iter.Seq2 that yields key-value pairs from the map.
|
| 81 |
+
func (m *Map[K, V]) Seq2() iter.Seq2[K, V] {
|
| 82 |
+
dst := make(map[K]V)
|
| 83 |
+
m.mu.RLock()
|
| 84 |
+
maps.Copy(dst, m.inner)
|
| 85 |
+
m.mu.RUnlock()
|
| 86 |
+
return func(yield func(K, V) bool) {
|
| 87 |
+
for k, v := range dst {
|
| 88 |
+
if !yield(k, v) {
|
| 89 |
+
return
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// Seq returns an iter.Seq that yields values from the map.
|
| 96 |
+
func (m *Map[K, V]) Seq() iter.Seq[V] {
|
| 97 |
+
return func(yield func(V) bool) {
|
| 98 |
+
for _, v := range m.Seq2() {
|
| 99 |
+
if !yield(v) {
|
| 100 |
+
return
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
var (
|
| 107 |
+
_ json.Unmarshaler = &Map[string, any]{}
|
| 108 |
+
_ json.Marshaler = &Map[string, any]{}
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
func (Map[K, V]) JSONSchemaAlias() any { //nolint
|
| 112 |
+
m := map[K]V{}
|
| 113 |
+
return m
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// UnmarshalJSON implements json.Unmarshaler.
|
| 117 |
+
func (m *Map[K, V]) UnmarshalJSON(data []byte) error {
|
| 118 |
+
m.mu.Lock()
|
| 119 |
+
defer m.mu.Unlock()
|
| 120 |
+
m.inner = make(map[K]V)
|
| 121 |
+
return json.Unmarshal(data, &m.inner)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
// MarshalJSON implements json.Marshaler.
|
| 125 |
+
func (m *Map[K, V]) MarshalJSON() ([]byte, error) {
|
| 126 |
+
m.mu.RLock()
|
| 127 |
+
defer m.mu.RUnlock()
|
| 128 |
+
return json.Marshal(m.inner)
|
| 129 |
+
}
|
projects/ui/crush/internal/csync/maps_test.go
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package csync
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"maps"
|
| 6 |
+
"sync"
|
| 7 |
+
"testing"
|
| 8 |
+
|
| 9 |
+
"github.com/stretchr/testify/require"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
func TestNewMap(t *testing.T) {
|
| 13 |
+
t.Parallel()
|
| 14 |
+
|
| 15 |
+
m := NewMap[string, int]()
|
| 16 |
+
require.NotNil(t, m)
|
| 17 |
+
require.NotNil(t, m.inner)
|
| 18 |
+
require.Equal(t, 0, m.Len())
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
func TestNewMapFrom(t *testing.T) {
|
| 22 |
+
t.Parallel()
|
| 23 |
+
|
| 24 |
+
original := map[string]int{
|
| 25 |
+
"key1": 1,
|
| 26 |
+
"key2": 2,
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
m := NewMapFrom(original)
|
| 30 |
+
require.NotNil(t, m)
|
| 31 |
+
require.Equal(t, original, m.inner)
|
| 32 |
+
require.Equal(t, 2, m.Len())
|
| 33 |
+
|
| 34 |
+
value, ok := m.Get("key1")
|
| 35 |
+
require.True(t, ok)
|
| 36 |
+
require.Equal(t, 1, value)
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
func TestMap_Set(t *testing.T) {
|
| 40 |
+
t.Parallel()
|
| 41 |
+
|
| 42 |
+
m := NewMap[string, int]()
|
| 43 |
+
|
| 44 |
+
m.Set("key1", 42)
|
| 45 |
+
value, ok := m.Get("key1")
|
| 46 |
+
require.True(t, ok)
|
| 47 |
+
require.Equal(t, 42, value)
|
| 48 |
+
require.Equal(t, 1, m.Len())
|
| 49 |
+
|
| 50 |
+
m.Set("key1", 100)
|
| 51 |
+
value, ok = m.Get("key1")
|
| 52 |
+
require.True(t, ok)
|
| 53 |
+
require.Equal(t, 100, value)
|
| 54 |
+
require.Equal(t, 1, m.Len())
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
func TestMap_GetOrSet(t *testing.T) {
|
| 58 |
+
t.Parallel()
|
| 59 |
+
|
| 60 |
+
m := NewMap[string, int]()
|
| 61 |
+
|
| 62 |
+
require.Equal(t, 42, m.GetOrSet("key1", func() int { return 42 }))
|
| 63 |
+
require.Equal(t, 42, m.GetOrSet("key1", func() int { return 99999 }))
|
| 64 |
+
require.Equal(t, 1, m.Len())
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
func TestMap_Get(t *testing.T) {
|
| 68 |
+
t.Parallel()
|
| 69 |
+
|
| 70 |
+
m := NewMap[string, int]()
|
| 71 |
+
|
| 72 |
+
value, ok := m.Get("nonexistent")
|
| 73 |
+
require.False(t, ok)
|
| 74 |
+
require.Equal(t, 0, value)
|
| 75 |
+
|
| 76 |
+
m.Set("key1", 42)
|
| 77 |
+
value, ok = m.Get("key1")
|
| 78 |
+
require.True(t, ok)
|
| 79 |
+
require.Equal(t, 42, value)
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
func TestMap_Del(t *testing.T) {
|
| 83 |
+
t.Parallel()
|
| 84 |
+
|
| 85 |
+
m := NewMap[string, int]()
|
| 86 |
+
m.Set("key1", 42)
|
| 87 |
+
m.Set("key2", 100)
|
| 88 |
+
|
| 89 |
+
require.Equal(t, 2, m.Len())
|
| 90 |
+
|
| 91 |
+
m.Del("key1")
|
| 92 |
+
_, ok := m.Get("key1")
|
| 93 |
+
require.False(t, ok)
|
| 94 |
+
require.Equal(t, 1, m.Len())
|
| 95 |
+
|
| 96 |
+
value, ok := m.Get("key2")
|
| 97 |
+
require.True(t, ok)
|
| 98 |
+
require.Equal(t, 100, value)
|
| 99 |
+
|
| 100 |
+
m.Del("nonexistent")
|
| 101 |
+
require.Equal(t, 1, m.Len())
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
func TestMap_Len(t *testing.T) {
|
| 105 |
+
t.Parallel()
|
| 106 |
+
|
| 107 |
+
m := NewMap[string, int]()
|
| 108 |
+
require.Equal(t, 0, m.Len())
|
| 109 |
+
|
| 110 |
+
m.Set("key1", 1)
|
| 111 |
+
require.Equal(t, 1, m.Len())
|
| 112 |
+
|
| 113 |
+
m.Set("key2", 2)
|
| 114 |
+
require.Equal(t, 2, m.Len())
|
| 115 |
+
|
| 116 |
+
m.Del("key1")
|
| 117 |
+
require.Equal(t, 1, m.Len())
|
| 118 |
+
|
| 119 |
+
m.Del("key2")
|
| 120 |
+
require.Equal(t, 0, m.Len())
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
func TestMap_Take(t *testing.T) {
|
| 124 |
+
t.Parallel()
|
| 125 |
+
|
| 126 |
+
m := NewMap[string, int]()
|
| 127 |
+
m.Set("key1", 42)
|
| 128 |
+
m.Set("key2", 100)
|
| 129 |
+
|
| 130 |
+
require.Equal(t, 2, m.Len())
|
| 131 |
+
|
| 132 |
+
value, ok := m.Take("key1")
|
| 133 |
+
require.True(t, ok)
|
| 134 |
+
require.Equal(t, 42, value)
|
| 135 |
+
require.Equal(t, 1, m.Len())
|
| 136 |
+
|
| 137 |
+
_, exists := m.Get("key1")
|
| 138 |
+
require.False(t, exists)
|
| 139 |
+
|
| 140 |
+
value, ok = m.Get("key2")
|
| 141 |
+
require.True(t, ok)
|
| 142 |
+
require.Equal(t, 100, value)
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
func TestMap_Take_NonexistentKey(t *testing.T) {
|
| 146 |
+
t.Parallel()
|
| 147 |
+
|
| 148 |
+
m := NewMap[string, int]()
|
| 149 |
+
m.Set("key1", 42)
|
| 150 |
+
|
| 151 |
+
value, ok := m.Take("nonexistent")
|
| 152 |
+
require.False(t, ok)
|
| 153 |
+
require.Equal(t, 0, value)
|
| 154 |
+
require.Equal(t, 1, m.Len())
|
| 155 |
+
|
| 156 |
+
value, ok = m.Get("key1")
|
| 157 |
+
require.True(t, ok)
|
| 158 |
+
require.Equal(t, 42, value)
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
func TestMap_Take_EmptyMap(t *testing.T) {
|
| 162 |
+
t.Parallel()
|
| 163 |
+
|
| 164 |
+
m := NewMap[string, int]()
|
| 165 |
+
|
| 166 |
+
value, ok := m.Take("key1")
|
| 167 |
+
require.False(t, ok)
|
| 168 |
+
require.Equal(t, 0, value)
|
| 169 |
+
require.Equal(t, 0, m.Len())
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
func TestMap_Take_SameKeyTwice(t *testing.T) {
|
| 173 |
+
t.Parallel()
|
| 174 |
+
|
| 175 |
+
m := NewMap[string, int]()
|
| 176 |
+
m.Set("key1", 42)
|
| 177 |
+
|
| 178 |
+
value, ok := m.Take("key1")
|
| 179 |
+
require.True(t, ok)
|
| 180 |
+
require.Equal(t, 42, value)
|
| 181 |
+
require.Equal(t, 0, m.Len())
|
| 182 |
+
|
| 183 |
+
value, ok = m.Take("key1")
|
| 184 |
+
require.False(t, ok)
|
| 185 |
+
require.Equal(t, 0, value)
|
| 186 |
+
require.Equal(t, 0, m.Len())
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
func TestMap_Seq2(t *testing.T) {
|
| 190 |
+
t.Parallel()
|
| 191 |
+
|
| 192 |
+
m := NewMap[string, int]()
|
| 193 |
+
m.Set("key1", 1)
|
| 194 |
+
m.Set("key2", 2)
|
| 195 |
+
m.Set("key3", 3)
|
| 196 |
+
|
| 197 |
+
collected := maps.Collect(m.Seq2())
|
| 198 |
+
|
| 199 |
+
require.Equal(t, 3, len(collected))
|
| 200 |
+
require.Equal(t, 1, collected["key1"])
|
| 201 |
+
require.Equal(t, 2, collected["key2"])
|
| 202 |
+
require.Equal(t, 3, collected["key3"])
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
func TestMap_Seq2_EarlyReturn(t *testing.T) {
|
| 206 |
+
t.Parallel()
|
| 207 |
+
|
| 208 |
+
m := NewMap[string, int]()
|
| 209 |
+
m.Set("key1", 1)
|
| 210 |
+
m.Set("key2", 2)
|
| 211 |
+
m.Set("key3", 3)
|
| 212 |
+
|
| 213 |
+
count := 0
|
| 214 |
+
for range m.Seq2() {
|
| 215 |
+
count++
|
| 216 |
+
if count == 2 {
|
| 217 |
+
break
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
require.Equal(t, 2, count)
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
func TestMap_Seq2_EmptyMap(t *testing.T) {
|
| 225 |
+
t.Parallel()
|
| 226 |
+
|
| 227 |
+
m := NewMap[string, int]()
|
| 228 |
+
|
| 229 |
+
count := 0
|
| 230 |
+
for range m.Seq2() {
|
| 231 |
+
count++
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
require.Equal(t, 0, count)
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
func TestMap_Seq(t *testing.T) {
|
| 238 |
+
t.Parallel()
|
| 239 |
+
|
| 240 |
+
m := NewMap[string, int]()
|
| 241 |
+
m.Set("key1", 1)
|
| 242 |
+
m.Set("key2", 2)
|
| 243 |
+
m.Set("key3", 3)
|
| 244 |
+
|
| 245 |
+
collected := make([]int, 0)
|
| 246 |
+
for v := range m.Seq() {
|
| 247 |
+
collected = append(collected, v)
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
require.Equal(t, 3, len(collected))
|
| 251 |
+
require.Contains(t, collected, 1)
|
| 252 |
+
require.Contains(t, collected, 2)
|
| 253 |
+
require.Contains(t, collected, 3)
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
func TestMap_Seq_EarlyReturn(t *testing.T) {
|
| 257 |
+
t.Parallel()
|
| 258 |
+
|
| 259 |
+
m := NewMap[string, int]()
|
| 260 |
+
m.Set("key1", 1)
|
| 261 |
+
m.Set("key2", 2)
|
| 262 |
+
m.Set("key3", 3)
|
| 263 |
+
|
| 264 |
+
count := 0
|
| 265 |
+
for range m.Seq() {
|
| 266 |
+
count++
|
| 267 |
+
if count == 2 {
|
| 268 |
+
break
|
| 269 |
+
}
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
require.Equal(t, 2, count)
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
func TestMap_Seq_EmptyMap(t *testing.T) {
|
| 276 |
+
t.Parallel()
|
| 277 |
+
|
| 278 |
+
m := NewMap[string, int]()
|
| 279 |
+
|
| 280 |
+
count := 0
|
| 281 |
+
for range m.Seq() {
|
| 282 |
+
count++
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
require.Equal(t, 0, count)
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
func TestMap_MarshalJSON(t *testing.T) {
|
| 289 |
+
t.Parallel()
|
| 290 |
+
|
| 291 |
+
m := NewMap[string, int]()
|
| 292 |
+
m.Set("key1", 1)
|
| 293 |
+
m.Set("key2", 2)
|
| 294 |
+
|
| 295 |
+
data, err := json.Marshal(m)
|
| 296 |
+
require.NoError(t, err)
|
| 297 |
+
|
| 298 |
+
result := &Map[string, int]{}
|
| 299 |
+
err = json.Unmarshal(data, result)
|
| 300 |
+
require.NoError(t, err)
|
| 301 |
+
require.Equal(t, 2, result.Len())
|
| 302 |
+
v1, _ := result.Get("key1")
|
| 303 |
+
v2, _ := result.Get("key2")
|
| 304 |
+
require.Equal(t, 1, v1)
|
| 305 |
+
require.Equal(t, 2, v2)
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
func TestMap_MarshalJSON_EmptyMap(t *testing.T) {
|
| 309 |
+
t.Parallel()
|
| 310 |
+
|
| 311 |
+
m := NewMap[string, int]()
|
| 312 |
+
|
| 313 |
+
data, err := json.Marshal(m)
|
| 314 |
+
require.NoError(t, err)
|
| 315 |
+
require.Equal(t, "{}", string(data))
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
func TestMap_UnmarshalJSON(t *testing.T) {
|
| 319 |
+
t.Parallel()
|
| 320 |
+
|
| 321 |
+
jsonData := `{"key1": 1, "key2": 2}`
|
| 322 |
+
|
| 323 |
+
m := NewMap[string, int]()
|
| 324 |
+
err := json.Unmarshal([]byte(jsonData), m)
|
| 325 |
+
require.NoError(t, err)
|
| 326 |
+
|
| 327 |
+
require.Equal(t, 2, m.Len())
|
| 328 |
+
value, ok := m.Get("key1")
|
| 329 |
+
require.True(t, ok)
|
| 330 |
+
require.Equal(t, 1, value)
|
| 331 |
+
|
| 332 |
+
value, ok = m.Get("key2")
|
| 333 |
+
require.True(t, ok)
|
| 334 |
+
require.Equal(t, 2, value)
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
func TestMap_UnmarshalJSON_EmptyJSON(t *testing.T) {
|
| 338 |
+
t.Parallel()
|
| 339 |
+
|
| 340 |
+
jsonData := `{}`
|
| 341 |
+
|
| 342 |
+
m := NewMap[string, int]()
|
| 343 |
+
err := json.Unmarshal([]byte(jsonData), m)
|
| 344 |
+
require.NoError(t, err)
|
| 345 |
+
require.Equal(t, 0, m.Len())
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
func TestMap_UnmarshalJSON_InvalidJSON(t *testing.T) {
|
| 349 |
+
t.Parallel()
|
| 350 |
+
|
| 351 |
+
jsonData := `{"key1": 1, "key2":}`
|
| 352 |
+
|
| 353 |
+
m := NewMap[string, int]()
|
| 354 |
+
err := json.Unmarshal([]byte(jsonData), m)
|
| 355 |
+
require.Error(t, err)
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
func TestMap_UnmarshalJSON_OverwritesExistingData(t *testing.T) {
|
| 359 |
+
t.Parallel()
|
| 360 |
+
|
| 361 |
+
m := NewMap[string, int]()
|
| 362 |
+
m.Set("existing", 999)
|
| 363 |
+
|
| 364 |
+
jsonData := `{"key1": 1, "key2": 2}`
|
| 365 |
+
err := json.Unmarshal([]byte(jsonData), m)
|
| 366 |
+
require.NoError(t, err)
|
| 367 |
+
|
| 368 |
+
require.Equal(t, 2, m.Len())
|
| 369 |
+
_, ok := m.Get("existing")
|
| 370 |
+
require.False(t, ok)
|
| 371 |
+
|
| 372 |
+
value, ok := m.Get("key1")
|
| 373 |
+
require.True(t, ok)
|
| 374 |
+
require.Equal(t, 1, value)
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
func TestMap_JSONRoundTrip(t *testing.T) {
|
| 378 |
+
t.Parallel()
|
| 379 |
+
|
| 380 |
+
original := NewMap[string, int]()
|
| 381 |
+
original.Set("key1", 1)
|
| 382 |
+
original.Set("key2", 2)
|
| 383 |
+
original.Set("key3", 3)
|
| 384 |
+
|
| 385 |
+
data, err := json.Marshal(original)
|
| 386 |
+
require.NoError(t, err)
|
| 387 |
+
|
| 388 |
+
restored := NewMap[string, int]()
|
| 389 |
+
err = json.Unmarshal(data, restored)
|
| 390 |
+
require.NoError(t, err)
|
| 391 |
+
|
| 392 |
+
require.Equal(t, original.Len(), restored.Len())
|
| 393 |
+
|
| 394 |
+
for k, v := range original.Seq2() {
|
| 395 |
+
restoredValue, ok := restored.Get(k)
|
| 396 |
+
require.True(t, ok)
|
| 397 |
+
require.Equal(t, v, restoredValue)
|
| 398 |
+
}
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
func TestMap_ConcurrentAccess(t *testing.T) {
|
| 402 |
+
t.Parallel()
|
| 403 |
+
|
| 404 |
+
m := NewMap[int, int]()
|
| 405 |
+
const numGoroutines = 100
|
| 406 |
+
const numOperations = 100
|
| 407 |
+
|
| 408 |
+
var wg sync.WaitGroup
|
| 409 |
+
wg.Add(numGoroutines)
|
| 410 |
+
|
| 411 |
+
for i := range numGoroutines {
|
| 412 |
+
go func(id int) {
|
| 413 |
+
defer wg.Done()
|
| 414 |
+
for j := range numOperations {
|
| 415 |
+
key := id*numOperations + j
|
| 416 |
+
m.Set(key, key*2)
|
| 417 |
+
value, ok := m.Get(key)
|
| 418 |
+
require.True(t, ok)
|
| 419 |
+
require.Equal(t, key*2, value)
|
| 420 |
+
}
|
| 421 |
+
}(i)
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
wg.Wait()
|
| 425 |
+
|
| 426 |
+
require.Equal(t, numGoroutines*numOperations, m.Len())
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
func TestMap_ConcurrentReadWrite(t *testing.T) {
|
| 430 |
+
t.Parallel()
|
| 431 |
+
|
| 432 |
+
m := NewMap[int, int]()
|
| 433 |
+
const numReaders = 50
|
| 434 |
+
const numWriters = 50
|
| 435 |
+
const numOperations = 100
|
| 436 |
+
|
| 437 |
+
for i := range 1000 {
|
| 438 |
+
m.Set(i, i)
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
var wg sync.WaitGroup
|
| 442 |
+
wg.Add(numReaders + numWriters)
|
| 443 |
+
|
| 444 |
+
for range numReaders {
|
| 445 |
+
go func() {
|
| 446 |
+
defer wg.Done()
|
| 447 |
+
for j := range numOperations {
|
| 448 |
+
key := j % 1000
|
| 449 |
+
value, ok := m.Get(key)
|
| 450 |
+
if ok {
|
| 451 |
+
require.Equal(t, key, value)
|
| 452 |
+
}
|
| 453 |
+
_ = m.Len()
|
| 454 |
+
}
|
| 455 |
+
}()
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
for i := range numWriters {
|
| 459 |
+
go func(id int) {
|
| 460 |
+
defer wg.Done()
|
| 461 |
+
for j := range numOperations {
|
| 462 |
+
key := 1000 + id*numOperations + j
|
| 463 |
+
m.Set(key, key)
|
| 464 |
+
if j%10 == 0 {
|
| 465 |
+
m.Del(key)
|
| 466 |
+
}
|
| 467 |
+
}
|
| 468 |
+
}(i)
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
wg.Wait()
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
func TestMap_ConcurrentSeq2(t *testing.T) {
|
| 475 |
+
t.Parallel()
|
| 476 |
+
|
| 477 |
+
m := NewMap[int, int]()
|
| 478 |
+
for i := range 100 {
|
| 479 |
+
m.Set(i, i*2)
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
var wg sync.WaitGroup
|
| 483 |
+
const numIterators = 10
|
| 484 |
+
|
| 485 |
+
wg.Add(numIterators)
|
| 486 |
+
for range numIterators {
|
| 487 |
+
go func() {
|
| 488 |
+
defer wg.Done()
|
| 489 |
+
count := 0
|
| 490 |
+
for k, v := range m.Seq2() {
|
| 491 |
+
require.Equal(t, k*2, v)
|
| 492 |
+
count++
|
| 493 |
+
}
|
| 494 |
+
require.Equal(t, 100, count)
|
| 495 |
+
}()
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
wg.Wait()
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
func TestMap_ConcurrentSeq(t *testing.T) {
|
| 502 |
+
t.Parallel()
|
| 503 |
+
|
| 504 |
+
m := NewMap[int, int]()
|
| 505 |
+
for i := range 100 {
|
| 506 |
+
m.Set(i, i*2)
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
var wg sync.WaitGroup
|
| 510 |
+
const numIterators = 10
|
| 511 |
+
|
| 512 |
+
wg.Add(numIterators)
|
| 513 |
+
for range numIterators {
|
| 514 |
+
go func() {
|
| 515 |
+
defer wg.Done()
|
| 516 |
+
count := 0
|
| 517 |
+
values := make(map[int]bool)
|
| 518 |
+
for v := range m.Seq() {
|
| 519 |
+
values[v] = true
|
| 520 |
+
count++
|
| 521 |
+
}
|
| 522 |
+
require.Equal(t, 100, count)
|
| 523 |
+
for i := range 100 {
|
| 524 |
+
require.True(t, values[i*2])
|
| 525 |
+
}
|
| 526 |
+
}()
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
wg.Wait()
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
func TestMap_ConcurrentTake(t *testing.T) {
|
| 533 |
+
t.Parallel()
|
| 534 |
+
|
| 535 |
+
m := NewMap[int, int]()
|
| 536 |
+
const numItems = 1000
|
| 537 |
+
|
| 538 |
+
for i := range numItems {
|
| 539 |
+
m.Set(i, i*2)
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
var wg sync.WaitGroup
|
| 543 |
+
const numWorkers = 10
|
| 544 |
+
taken := make([][]int, numWorkers)
|
| 545 |
+
|
| 546 |
+
wg.Add(numWorkers)
|
| 547 |
+
for i := range numWorkers {
|
| 548 |
+
go func(workerID int) {
|
| 549 |
+
defer wg.Done()
|
| 550 |
+
taken[workerID] = make([]int, 0)
|
| 551 |
+
for j := workerID; j < numItems; j += numWorkers {
|
| 552 |
+
if value, ok := m.Take(j); ok {
|
| 553 |
+
taken[workerID] = append(taken[workerID], value)
|
| 554 |
+
}
|
| 555 |
+
}
|
| 556 |
+
}(i)
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
wg.Wait()
|
| 560 |
+
|
| 561 |
+
require.Equal(t, 0, m.Len())
|
| 562 |
+
|
| 563 |
+
allTaken := make(map[int]bool)
|
| 564 |
+
for _, workerTaken := range taken {
|
| 565 |
+
for _, value := range workerTaken {
|
| 566 |
+
require.False(t, allTaken[value], "Value %d was taken multiple times", value)
|
| 567 |
+
allTaken[value] = true
|
| 568 |
+
}
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
require.Equal(t, numItems, len(allTaken))
|
| 572 |
+
for i := range numItems {
|
| 573 |
+
require.True(t, allTaken[i*2], "Expected value %d to be taken", i*2)
|
| 574 |
+
}
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
func TestMap_TypeSafety(t *testing.T) {
|
| 578 |
+
t.Parallel()
|
| 579 |
+
|
| 580 |
+
stringIntMap := NewMap[string, int]()
|
| 581 |
+
stringIntMap.Set("key", 42)
|
| 582 |
+
value, ok := stringIntMap.Get("key")
|
| 583 |
+
require.True(t, ok)
|
| 584 |
+
require.Equal(t, 42, value)
|
| 585 |
+
|
| 586 |
+
intStringMap := NewMap[int, string]()
|
| 587 |
+
intStringMap.Set(42, "value")
|
| 588 |
+
strValue, ok := intStringMap.Get(42)
|
| 589 |
+
require.True(t, ok)
|
| 590 |
+
require.Equal(t, "value", strValue)
|
| 591 |
+
|
| 592 |
+
structMap := NewMap[string, struct{ Name string }]()
|
| 593 |
+
structMap.Set("key", struct{ Name string }{Name: "test"})
|
| 594 |
+
structValue, ok := structMap.Get("key")
|
| 595 |
+
require.True(t, ok)
|
| 596 |
+
require.Equal(t, "test", structValue.Name)
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
+
func TestMap_InterfaceCompliance(t *testing.T) {
|
| 600 |
+
t.Parallel()
|
| 601 |
+
|
| 602 |
+
var _ json.Marshaler = &Map[string, any]{}
|
| 603 |
+
var _ json.Unmarshaler = &Map[string, any]{}
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
func BenchmarkMap_Set(b *testing.B) {
|
| 607 |
+
m := NewMap[int, int]()
|
| 608 |
+
|
| 609 |
+
for i := 0; b.Loop(); i++ {
|
| 610 |
+
m.Set(i, i*2)
|
| 611 |
+
}
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
func BenchmarkMap_Get(b *testing.B) {
|
| 615 |
+
m := NewMap[int, int]()
|
| 616 |
+
for i := range 1000 {
|
| 617 |
+
m.Set(i, i*2)
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
for i := 0; b.Loop(); i++ {
|
| 621 |
+
m.Get(i % 1000)
|
| 622 |
+
}
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
func BenchmarkMap_Seq2(b *testing.B) {
|
| 626 |
+
m := NewMap[int, int]()
|
| 627 |
+
for i := range 1000 {
|
| 628 |
+
m.Set(i, i*2)
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
for b.Loop() {
|
| 632 |
+
for range m.Seq2() {
|
| 633 |
+
}
|
| 634 |
+
}
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
func BenchmarkMap_Seq(b *testing.B) {
|
| 638 |
+
m := NewMap[int, int]()
|
| 639 |
+
for i := range 1000 {
|
| 640 |
+
m.Set(i, i*2)
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
for b.Loop() {
|
| 644 |
+
for range m.Seq() {
|
| 645 |
+
}
|
| 646 |
+
}
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
func BenchmarkMap_Take(b *testing.B) {
|
| 650 |
+
m := NewMap[int, int]()
|
| 651 |
+
for i := range 1000 {
|
| 652 |
+
m.Set(i, i*2)
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
+
b.ResetTimer()
|
| 656 |
+
for i := 0; b.Loop(); i++ {
|
| 657 |
+
key := i % 1000
|
| 658 |
+
m.Take(key)
|
| 659 |
+
if i%1000 == 999 {
|
| 660 |
+
b.StopTimer()
|
| 661 |
+
for j := range 1000 {
|
| 662 |
+
m.Set(j, j*2)
|
| 663 |
+
}
|
| 664 |
+
b.StartTimer()
|
| 665 |
+
}
|
| 666 |
+
}
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
func BenchmarkMap_ConcurrentReadWrite(b *testing.B) {
|
| 670 |
+
m := NewMap[int, int]()
|
| 671 |
+
for i := range 1000 {
|
| 672 |
+
m.Set(i, i*2)
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
b.ResetTimer()
|
| 676 |
+
b.RunParallel(func(pb *testing.PB) {
|
| 677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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package csync
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"iter"
|
| 5 |
+
"slices"
|
| 6 |
+
"sync"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
// LazySlice is a thread-safe lazy-loaded slice.
|
| 10 |
+
type LazySlice[K any] struct {
|
| 11 |
+
inner []K
|
| 12 |
+
wg sync.WaitGroup
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
// NewLazySlice creates a new slice and runs the [load] function in a goroutine
|
| 16 |
+
// to populate it.
|
| 17 |
+
func NewLazySlice[K any](load func() []K) *LazySlice[K] {
|
| 18 |
+
s := &LazySlice[K]{}
|
| 19 |
+
s.wg.Go(func() {
|
| 20 |
+
s.inner = load()
|
| 21 |
+
})
|
| 22 |
+
return s
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
// Seq returns an iterator that yields elements from the slice.
|
| 26 |
+
func (s *LazySlice[K]) Seq() iter.Seq[K] {
|
| 27 |
+
s.wg.Wait()
|
| 28 |
+
return func(yield func(K) bool) {
|
| 29 |
+
for _, v := range s.inner {
|
| 30 |
+
if !yield(v) {
|
| 31 |
+
return
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// Slice is a thread-safe slice implementation that provides concurrent access.
|
| 38 |
+
type Slice[T any] struct {
|
| 39 |
+
inner []T
|
| 40 |
+
mu sync.RWMutex
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
// NewSlice creates a new thread-safe slice.
|
| 44 |
+
func NewSlice[T any]() *Slice[T] {
|
| 45 |
+
return &Slice[T]{
|
| 46 |
+
inner: make([]T, 0),
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
// NewSliceFrom creates a new thread-safe slice from an existing slice.
|
| 51 |
+
func NewSliceFrom[T any](s []T) *Slice[T] {
|
| 52 |
+
inner := make([]T, len(s))
|
| 53 |
+
copy(inner, s)
|
| 54 |
+
return &Slice[T]{
|
| 55 |
+
inner: inner,
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// Append adds an element to the end of the slice.
|
| 60 |
+
func (s *Slice[T]) Append(items ...T) {
|
| 61 |
+
s.mu.Lock()
|
| 62 |
+
defer s.mu.Unlock()
|
| 63 |
+
s.inner = append(s.inner, items...)
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// Prepend adds an element to the beginning of the slice.
|
| 67 |
+
func (s *Slice[T]) Prepend(item T) {
|
| 68 |
+
s.mu.Lock()
|
| 69 |
+
defer s.mu.Unlock()
|
| 70 |
+
s.inner = append([]T{item}, s.inner...)
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// Delete removes the element at the specified index.
|
| 74 |
+
func (s *Slice[T]) Delete(index int) bool {
|
| 75 |
+
s.mu.Lock()
|
| 76 |
+
defer s.mu.Unlock()
|
| 77 |
+
if index < 0 || index >= len(s.inner) {
|
| 78 |
+
return false
|
| 79 |
+
}
|
| 80 |
+
s.inner = slices.Delete(s.inner, index, index+1)
|
| 81 |
+
return true
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
// Get returns the element at the specified index.
|
| 85 |
+
func (s *Slice[T]) Get(index int) (T, bool) {
|
| 86 |
+
s.mu.RLock()
|
| 87 |
+
defer s.mu.RUnlock()
|
| 88 |
+
var zero T
|
| 89 |
+
if index < 0 || index >= len(s.inner) {
|
| 90 |
+
return zero, false
|
| 91 |
+
}
|
| 92 |
+
return s.inner[index], true
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// Set updates the element at the specified index.
|
| 96 |
+
func (s *Slice[T]) Set(index int, item T) bool {
|
| 97 |
+
s.mu.Lock()
|
| 98 |
+
defer s.mu.Unlock()
|
| 99 |
+
if index < 0 || index >= len(s.inner) {
|
| 100 |
+
return false
|
| 101 |
+
}
|
| 102 |
+
s.inner[index] = item
|
| 103 |
+
return true
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
// Len returns the number of elements in the slice.
|
| 107 |
+
func (s *Slice[T]) Len() int {
|
| 108 |
+
s.mu.RLock()
|
| 109 |
+
defer s.mu.RUnlock()
|
| 110 |
+
return len(s.inner)
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
// SetSlice replaces the entire slice with a new one.
|
| 114 |
+
func (s *Slice[T]) SetSlice(items []T) {
|
| 115 |
+
s.mu.Lock()
|
| 116 |
+
defer s.mu.Unlock()
|
| 117 |
+
s.inner = make([]T, len(items))
|
| 118 |
+
copy(s.inner, items)
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
// Seq returns an iterator that yields elements from the slice.
|
| 122 |
+
func (s *Slice[T]) Seq() iter.Seq[T] {
|
| 123 |
+
return func(yield func(T) bool) {
|
| 124 |
+
for _, v := range s.Seq2() {
|
| 125 |
+
if !yield(v) {
|
| 126 |
+
return
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
// Seq2 returns an iterator that yields index-value pairs from the slice.
|
| 133 |
+
func (s *Slice[T]) Seq2() iter.Seq2[int, T] {
|
| 134 |
+
s.mu.RLock()
|
| 135 |
+
items := make([]T, len(s.inner))
|
| 136 |
+
copy(items, s.inner)
|
| 137 |
+
s.mu.RUnlock()
|
| 138 |
+
return func(yield func(int, T) bool) {
|
| 139 |
+
for i, v := range items {
|
| 140 |
+
if !yield(i, v) {
|
| 141 |
+
return
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
}
|
projects/ui/crush/internal/csync/slices_test.go
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package csync
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"slices"
|
| 5 |
+
"sync"
|
| 6 |
+
"sync/atomic"
|
| 7 |
+
"testing"
|
| 8 |
+
"testing/synctest"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
"github.com/stretchr/testify/require"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
func TestLazySlice_Seq(t *testing.T) {
|
| 15 |
+
t.Parallel()
|
| 16 |
+
|
| 17 |
+
synctest.Test(t, func(t *testing.T) {
|
| 18 |
+
t.Helper()
|
| 19 |
+
data := []string{"a", "b", "c"}
|
| 20 |
+
s := NewLazySlice(func() []string {
|
| 21 |
+
time.Sleep(10 * time.Millisecond) // Small delay to ensure loading happens
|
| 22 |
+
return data
|
| 23 |
+
})
|
| 24 |
+
require.Equal(t, data, slices.Collect(s.Seq()))
|
| 25 |
+
})
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func TestLazySlice_SeqWaitsForLoading(t *testing.T) {
|
| 29 |
+
t.Parallel()
|
| 30 |
+
synctest.Test(t, func(t *testing.T) {
|
| 31 |
+
t.Helper()
|
| 32 |
+
|
| 33 |
+
var loaded atomic.Bool
|
| 34 |
+
data := []string{"x", "y", "z"}
|
| 35 |
+
|
| 36 |
+
s := NewLazySlice(func() []string {
|
| 37 |
+
time.Sleep(100 * time.Millisecond)
|
| 38 |
+
loaded.Store(true)
|
| 39 |
+
return data
|
| 40 |
+
})
|
| 41 |
+
|
| 42 |
+
require.False(t, loaded.Load(), "should not be loaded immediately")
|
| 43 |
+
require.Equal(t, data, slices.Collect(s.Seq()))
|
| 44 |
+
require.True(t, loaded.Load(), "should be loaded after Seq")
|
| 45 |
+
})
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
func TestLazySlice_EmptySlice(t *testing.T) {
|
| 49 |
+
t.Parallel()
|
| 50 |
+
s := NewLazySlice(func() []string {
|
| 51 |
+
return []string{}
|
| 52 |
+
})
|
| 53 |
+
require.Empty(t, slices.Collect(s.Seq()))
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func TestLazySlice_EarlyBreak(t *testing.T) {
|
| 57 |
+
t.Parallel()
|
| 58 |
+
|
| 59 |
+
synctest.Test(t, func(t *testing.T) {
|
| 60 |
+
t.Helper()
|
| 61 |
+
data := []string{"a", "b", "c", "d", "e"}
|
| 62 |
+
s := NewLazySlice(func() []string {
|
| 63 |
+
time.Sleep(10 * time.Millisecond) // Small delay to ensure loading happens
|
| 64 |
+
return data
|
| 65 |
+
})
|
| 66 |
+
|
| 67 |
+
var result []string
|
| 68 |
+
for v := range s.Seq() {
|
| 69 |
+
result = append(result, v)
|
| 70 |
+
if len(result) == 2 {
|
| 71 |
+
break
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
require.Equal(t, []string{"a", "b"}, result)
|
| 76 |
+
})
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
func TestSlice(t *testing.T) {
|
| 80 |
+
t.Run("NewSlice", func(t *testing.T) {
|
| 81 |
+
s := NewSlice[int]()
|
| 82 |
+
require.Equal(t, 0, s.Len())
|
| 83 |
+
})
|
| 84 |
+
|
| 85 |
+
t.Run("NewSliceFrom", func(t *testing.T) {
|
| 86 |
+
original := []int{1, 2, 3}
|
| 87 |
+
s := NewSliceFrom(original)
|
| 88 |
+
require.Equal(t, 3, s.Len())
|
| 89 |
+
|
| 90 |
+
// Verify it's a copy, not a reference
|
| 91 |
+
original[0] = 999
|
| 92 |
+
val, ok := s.Get(0)
|
| 93 |
+
require.True(t, ok)
|
| 94 |
+
require.Equal(t, 1, val)
|
| 95 |
+
})
|
| 96 |
+
|
| 97 |
+
t.Run("Append", func(t *testing.T) {
|
| 98 |
+
s := NewSlice[string]()
|
| 99 |
+
s.Append("hello")
|
| 100 |
+
s.Append("world")
|
| 101 |
+
|
| 102 |
+
require.Equal(t, 2, s.Len())
|
| 103 |
+
val, ok := s.Get(0)
|
| 104 |
+
require.True(t, ok)
|
| 105 |
+
require.Equal(t, "hello", val)
|
| 106 |
+
|
| 107 |
+
val, ok = s.Get(1)
|
| 108 |
+
require.True(t, ok)
|
| 109 |
+
require.Equal(t, "world", val)
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
t.Run("Prepend", func(t *testing.T) {
|
| 113 |
+
s := NewSlice[string]()
|
| 114 |
+
s.Append("world")
|
| 115 |
+
s.Prepend("hello")
|
| 116 |
+
|
| 117 |
+
require.Equal(t, 2, s.Len())
|
| 118 |
+
val, ok := s.Get(0)
|
| 119 |
+
require.True(t, ok)
|
| 120 |
+
require.Equal(t, "hello", val)
|
| 121 |
+
|
| 122 |
+
val, ok = s.Get(1)
|
| 123 |
+
require.True(t, ok)
|
| 124 |
+
require.Equal(t, "world", val)
|
| 125 |
+
})
|
| 126 |
+
|
| 127 |
+
t.Run("Delete", func(t *testing.T) {
|
| 128 |
+
s := NewSliceFrom([]int{1, 2, 3, 4, 5})
|
| 129 |
+
|
| 130 |
+
// Delete middle element
|
| 131 |
+
ok := s.Delete(2)
|
| 132 |
+
require.True(t, ok)
|
| 133 |
+
require.Equal(t, 4, s.Len())
|
| 134 |
+
|
| 135 |
+
expected := []int{1, 2, 4, 5}
|
| 136 |
+
actual := slices.Collect(s.Seq())
|
| 137 |
+
require.Equal(t, expected, actual)
|
| 138 |
+
|
| 139 |
+
// Delete out of bounds
|
| 140 |
+
ok = s.Delete(10)
|
| 141 |
+
require.False(t, ok)
|
| 142 |
+
require.Equal(t, 4, s.Len())
|
| 143 |
+
|
| 144 |
+
// Delete negative index
|
| 145 |
+
ok = s.Delete(-1)
|
| 146 |
+
require.False(t, ok)
|
| 147 |
+
require.Equal(t, 4, s.Len())
|
| 148 |
+
})
|
| 149 |
+
|
| 150 |
+
t.Run("Get", func(t *testing.T) {
|
| 151 |
+
s := NewSliceFrom([]string{"a", "b", "c"})
|
| 152 |
+
|
| 153 |
+
val, ok := s.Get(1)
|
| 154 |
+
require.True(t, ok)
|
| 155 |
+
require.Equal(t, "b", val)
|
| 156 |
+
|
| 157 |
+
// Out of bounds
|
| 158 |
+
_, ok = s.Get(10)
|
| 159 |
+
require.False(t, ok)
|
| 160 |
+
|
| 161 |
+
// Negative index
|
| 162 |
+
_, ok = s.Get(-1)
|
| 163 |
+
require.False(t, ok)
|
| 164 |
+
})
|
| 165 |
+
|
| 166 |
+
t.Run("Set", func(t *testing.T) {
|
| 167 |
+
s := NewSliceFrom([]string{"a", "b", "c"})
|
| 168 |
+
|
| 169 |
+
ok := s.Set(1, "modified")
|
| 170 |
+
require.True(t, ok)
|
| 171 |
+
|
| 172 |
+
val, ok := s.Get(1)
|
| 173 |
+
require.True(t, ok)
|
| 174 |
+
require.Equal(t, "modified", val)
|
| 175 |
+
|
| 176 |
+
// Out of bounds
|
| 177 |
+
ok = s.Set(10, "invalid")
|
| 178 |
+
require.False(t, ok)
|
| 179 |
+
|
| 180 |
+
// Negative index
|
| 181 |
+
ok = s.Set(-1, "invalid")
|
| 182 |
+
require.False(t, ok)
|
| 183 |
+
})
|
| 184 |
+
|
| 185 |
+
t.Run("SetSlice", func(t *testing.T) {
|
| 186 |
+
s := NewSlice[int]()
|
| 187 |
+
s.Append(1)
|
| 188 |
+
s.Append(2)
|
| 189 |
+
|
| 190 |
+
newItems := []int{10, 20, 30}
|
| 191 |
+
s.SetSlice(newItems)
|
| 192 |
+
|
| 193 |
+
require.Equal(t, 3, s.Len())
|
| 194 |
+
require.Equal(t, newItems, slices.Collect(s.Seq()))
|
| 195 |
+
|
| 196 |
+
// Verify it's a copy
|
| 197 |
+
newItems[0] = 999
|
| 198 |
+
val, ok := s.Get(0)
|
| 199 |
+
require.True(t, ok)
|
| 200 |
+
require.Equal(t, 10, val)
|
| 201 |
+
})
|
| 202 |
+
|
| 203 |
+
t.Run("Slice", func(t *testing.T) {
|
| 204 |
+
original := []int{1, 2, 3}
|
| 205 |
+
s := NewSliceFrom(original)
|
| 206 |
+
|
| 207 |
+
copied := slices.Collect(s.Seq())
|
| 208 |
+
require.Equal(t, original, copied)
|
| 209 |
+
|
| 210 |
+
// Verify it's a copy
|
| 211 |
+
copied[0] = 999
|
| 212 |
+
val, ok := s.Get(0)
|
| 213 |
+
require.True(t, ok)
|
| 214 |
+
require.Equal(t, 1, val)
|
| 215 |
+
})
|
| 216 |
+
|
| 217 |
+
t.Run("Seq", func(t *testing.T) {
|
| 218 |
+
s := NewSliceFrom([]int{1, 2, 3})
|
| 219 |
+
|
| 220 |
+
var result []int
|
| 221 |
+
for v := range s.Seq() {
|
| 222 |
+
result = append(result, v)
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
require.Equal(t, []int{1, 2, 3}, result)
|
| 226 |
+
})
|
| 227 |
+
|
| 228 |
+
t.Run("SeqWithIndex", func(t *testing.T) {
|
| 229 |
+
s := NewSliceFrom([]string{"a", "b", "c"})
|
| 230 |
+
|
| 231 |
+
var indices []int
|
| 232 |
+
var values []string
|
| 233 |
+
for i, v := range s.Seq2() {
|
| 234 |
+
indices = append(indices, i)
|
| 235 |
+
values = append(values, v)
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
require.Equal(t, []int{0, 1, 2}, indices)
|
| 239 |
+
require.Equal(t, []string{"a", "b", "c"}, values)
|
| 240 |
+
})
|
| 241 |
+
|
| 242 |
+
t.Run("ConcurrentAccess", func(t *testing.T) {
|
| 243 |
+
s := NewSlice[int]()
|
| 244 |
+
const numGoroutines = 100
|
| 245 |
+
const itemsPerGoroutine = 10
|
| 246 |
+
|
| 247 |
+
var wg sync.WaitGroup
|
| 248 |
+
|
| 249 |
+
// Concurrent appends
|
| 250 |
+
for i := range numGoroutines {
|
| 251 |
+
wg.Add(2)
|
| 252 |
+
go func(start int) {
|
| 253 |
+
defer wg.Done()
|
| 254 |
+
for j := range itemsPerGoroutine {
|
| 255 |
+
s.Append(start*itemsPerGoroutine + j)
|
| 256 |
+
}
|
| 257 |
+
}(i)
|
| 258 |
+
go func() {
|
| 259 |
+
defer wg.Done()
|
| 260 |
+
for range itemsPerGoroutine {
|
| 261 |
+
s.Len() // Just read the length
|
| 262 |
+
}
|
| 263 |
+
}()
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
wg.Wait()
|
| 267 |
+
|
| 268 |
+
// Should have all items
|
| 269 |
+
require.Equal(t, numGoroutines*itemsPerGoroutine, s.Len())
|
| 270 |
+
})
|
| 271 |
+
}
|
projects/ui/crush/internal/db/connect.go
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package db
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"database/sql"
|
| 6 |
+
"fmt"
|
| 7 |
+
"log/slog"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
|
| 10 |
+
_ "github.com/ncruces/go-sqlite3/driver"
|
| 11 |
+
_ "github.com/ncruces/go-sqlite3/embed"
|
| 12 |
+
|
| 13 |
+
"github.com/pressly/goose/v3"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
func Connect(ctx context.Context, dataDir string) (*sql.DB, error) {
|
| 17 |
+
if dataDir == "" {
|
| 18 |
+
return nil, fmt.Errorf("data.dir is not set")
|
| 19 |
+
}
|
| 20 |
+
dbPath := filepath.Join(dataDir, "crush.db")
|
| 21 |
+
// Open the SQLite database
|
| 22 |
+
db, err := sql.Open("sqlite3", dbPath)
|
| 23 |
+
if err != nil {
|
| 24 |
+
return nil, fmt.Errorf("failed to open database: %w", err)
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
// Verify connection
|
| 28 |
+
if err = db.PingContext(ctx); err != nil {
|
| 29 |
+
db.Close()
|
| 30 |
+
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// Set pragmas for better performance
|
| 34 |
+
pragmas := []string{
|
| 35 |
+
"PRAGMA foreign_keys = ON;",
|
| 36 |
+
"PRAGMA journal_mode = WAL;",
|
| 37 |
+
"PRAGMA page_size = 4096;",
|
| 38 |
+
"PRAGMA cache_size = -8000;",
|
| 39 |
+
"PRAGMA synchronous = NORMAL;",
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
for _, pragma := range pragmas {
|
| 43 |
+
if _, err = db.ExecContext(ctx, pragma); err != nil {
|
| 44 |
+
slog.Error("Failed to set pragma", pragma, err)
|
| 45 |
+
} else {
|
| 46 |
+
slog.Debug("Set pragma", "pragma", pragma)
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
goose.SetBaseFS(FS)
|
| 51 |
+
|
| 52 |
+
if err := goose.SetDialect("sqlite3"); err != nil {
|
| 53 |
+
slog.Error("Failed to set dialect", "error", err)
|
| 54 |
+
return nil, fmt.Errorf("failed to set dialect: %w", err)
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
if err := goose.Up(db, "migrations"); err != nil {
|
| 58 |
+
slog.Error("Failed to apply migrations", "error", err)
|
| 59 |
+
return nil, fmt.Errorf("failed to apply migrations: %w", err)
|
| 60 |
+
}
|
| 61 |
+
return db, nil
|
| 62 |
+
}
|