File size: 11,935 Bytes
6a7089a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 | package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
var clipboardExecCommand = exec.Command
var configCmd = &cobra.Command{
Use: "config",
Short: "Manage configuration",
Run: func(cmd *cobra.Command, args []string) {
handleConfigOverview(loadConfig())
},
}
func init() {
configCmd.GroupID = "config"
configCmd.AddCommand(&cobra.Command{
Use: "show",
Short: "Display current configuration",
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
cli.HandleConfigShow(cfg)
},
})
configCmd.AddCommand(&cobra.Command{
Use: "init",
Short: "Initialize a new config file",
Run: func(cmd *cobra.Command, args []string) {
handleConfigInit()
},
})
configCmd.AddCommand(&cobra.Command{
Use: "path",
Short: "Show config file path",
Run: func(cmd *cobra.Command, args []string) {
handleConfigPath()
},
})
configCmd.AddCommand(&cobra.Command{
Use: "validate",
Short: "Validate config file",
Run: func(cmd *cobra.Command, args []string) {
handleConfigValidate()
},
})
configCmd.AddCommand(&cobra.Command{
Use: "get <path>",
Short: "Get a config value (e.g., server.port)",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
handleConfigGet(args[0])
},
})
configCmd.AddCommand(&cobra.Command{
Use: "set <path> <val>",
Short: "Set a config value (e.g., server.port 8080)",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
handleConfigSet(args[0], args[1])
},
})
configCmd.AddCommand(&cobra.Command{
Use: "patch <json>",
Short: "Merge JSON into config",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
handleConfigPatch(args[0])
},
})
rootCmd.AddCommand(configCmd)
}
func handleConfigOverview(cfg *config.RuntimeConfig) {
_, configPath, err := config.LoadFileConfig()
if err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("Error loading config path: %v", err)))
os.Exit(1)
}
dashPort := cfg.Port
if dashPort == "" {
dashPort = "9870"
}
dashboardURL := fmt.Sprintf("http://localhost:%s", dashPort)
running := server.CheckPinchTabRunning(dashPort, cfg.Token)
for {
fmt.Print(renderConfigOverview(cfg, configPath, dashboardURL, running))
if !isInteractiveTerminal() {
return
}
nextCfg, changed, done, err := promptConfigEdit(cfg)
if err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
fmt.Println()
continue
}
if done {
return
}
if !changed {
fmt.Println()
continue
}
cfg = nextCfg
dashPort = cfg.Port
if dashPort == "" {
dashPort = "9870"
}
dashboardURL = fmt.Sprintf("http://localhost:%s", dashPort)
running = server.CheckPinchTabRunning(dashPort, cfg.Token)
fmt.Println()
}
}
func renderConfigOverview(cfg *config.RuntimeConfig, configPath, dashboardURL string, running bool) string {
out := ""
out += cli.StyleStdout(cli.HeadingStyle, "Config") + "\n\n"
out += fmt.Sprintf(" 1. %-18s %s\n", "Strategy", cli.StyleStdout(cli.ValueStyle, cfg.Strategy))
out += fmt.Sprintf(" 2. %-18s %s\n", "Allocation policy", cli.StyleStdout(cli.ValueStyle, cfg.AllocationPolicy))
out += fmt.Sprintf(" 3. %-18s %s\n", "Stealth level", cli.StyleStdout(cli.ValueStyle, cfg.StealthLevel))
out += fmt.Sprintf(" 4. %-18s %s\n", "Tab eviction", cli.StyleStdout(cli.ValueStyle, cfg.TabEvictionPolicy))
out += fmt.Sprintf(" 5. %-18s %s\n", "Copy token", cli.StyleStdout(cli.MutedStyle, "clipboard"))
out += "\n"
out += cli.StyleStdout(cli.HeadingStyle, "More") + "\n\n"
out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "File:"), cli.StyleStdout(cli.ValueStyle, configPath))
out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Token:"), cli.StyleStdout(cli.ValueStyle, config.MaskToken(cfg.Token)))
if running {
out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Dashboard:"), cli.StyleStdout(cli.ValueStyle, dashboardURL))
} else {
out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Dashboard:"), cli.StyleStdout(cli.MutedStyle, "not running"))
}
if isInteractiveTerminal() {
out += "\n"
out += cli.StyleStdout(cli.MutedStyle, "Edit item (1-5, blank to exit):") + " "
}
out += "\n"
return out
}
func promptConfigEdit(cfg *config.RuntimeConfig) (*config.RuntimeConfig, bool, bool, error) {
choice, err := promptInput("", "")
if err != nil {
return nil, false, false, err
}
choice = strings.TrimSpace(choice)
if choice == "" {
return nil, false, true, nil
}
switch choice {
case "1":
nextCfg, changed, err := editConfigSelection("Instance strategy", "multiInstance.strategy", cfg.Strategy, config.ValidStrategies())
return nextCfg, changed, false, err
case "2":
nextCfg, changed, err := editConfigSelection("Allocation policy", "multiInstance.allocationPolicy", cfg.AllocationPolicy, config.ValidAllocationPolicies())
return nextCfg, changed, false, err
case "3":
nextCfg, changed, err := editConfigSelection("Default stealth level", "instanceDefaults.stealthLevel", cfg.StealthLevel, config.ValidStealthLevels())
return nextCfg, changed, false, err
case "4":
nextCfg, changed, err := editConfigSelection("Default tab eviction", "instanceDefaults.tabEvictionPolicy", cfg.TabEvictionPolicy, config.ValidEvictionPolicies())
return nextCfg, changed, false, err
case "5":
if err := copyConfigToken(cfg.Token); err != nil {
return nil, false, false, err
}
return nil, false, false, nil
default:
return nil, false, false, fmt.Errorf("invalid selection %q", choice)
}
}
func editConfigSelection(title, path, current string, values []string) (*config.RuntimeConfig, bool, error) {
options := make([]menuOption, 0, len(values)+1)
for _, value := range values {
label := value
if value == current {
label += " (current)"
}
options = append(options, menuOption{label: label, value: value})
}
options = append(options, menuOption{label: "Cancel", value: "cancel"})
picked, err := promptSelect(title, options)
if err != nil {
return nil, false, err
}
if picked == "" || picked == "cancel" {
return nil, false, nil
}
nextCfg, changed, err := updateConfigValue(path, picked)
if err != nil {
return nil, false, err
}
if changed {
fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Updated %s to %s", path, picked)))
fmt.Println(cli.StyleStdout(cli.MutedStyle, "Restart PinchTab to apply file-based changes."))
}
return nextCfg, changed, nil
}
func copyConfigToken(token string) error {
if strings.TrimSpace(token) == "" {
return fmt.Errorf("server token is empty")
}
if err := copyToClipboard(token); err == nil {
fmt.Println(cli.StyleStdout(cli.SuccessStyle, "Token copied to clipboard."))
return nil
}
fmt.Println(cli.StyleStdout(cli.WarningStyle, "Clipboard unavailable; copy the token manually:"))
fmt.Println(cli.StyleStdout(cli.ValueStyle, token))
return nil
}
func copyToClipboard(text string) error {
candidates := clipboardCommands()
var lastErr error
for _, candidate := range candidates {
if _, err := exec.LookPath(candidate.name); err != nil {
lastErr = err
continue
}
cmd := clipboardExecCommand(candidate.name, candidate.args...)
cmd.Stdin = strings.NewReader(text)
if output, err := cmd.CombinedOutput(); err != nil {
if len(strings.TrimSpace(string(output))) > 0 {
lastErr = fmt.Errorf("%s: %s", err, strings.TrimSpace(string(output)))
} else {
lastErr = err
}
continue
}
return nil
}
if lastErr == nil {
return fmt.Errorf("no clipboard command available")
}
return lastErr
}
type clipboardCommand struct {
name string
args []string
}
func clipboardCommands() []clipboardCommand {
switch runtime.GOOS {
case "darwin":
return []clipboardCommand{{name: "pbcopy"}}
case "windows":
return []clipboardCommand{{name: "clip"}}
default:
return []clipboardCommand{
{name: "wl-copy"},
{name: "xclip", args: []string{"-selection", "clipboard"}},
{name: "xsel", args: []string{"--clipboard", "--input"}},
}
}
}
func handleConfigInit() {
configPath := os.Getenv("PINCHTAB_CONFIG")
if configPath == "" {
configPath = config.DefaultConfigPath()
}
if _, err := os.Stat(configPath); err == nil {
fmt.Printf("Config file already exists at %s\n", configPath)
fmt.Print("Overwrite? (y/N): ")
var response string
_, _ = fmt.Scanln(&response)
if response != "y" && response != "Y" {
return
}
}
if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
fmt.Printf("Error creating directory: %v\n", err)
os.Exit(1)
}
fc := config.DefaultFileConfig()
token, err := config.GenerateAuthToken()
if err != nil {
fmt.Printf("Error generating auth token: %v\n", err)
os.Exit(1)
}
fc.Server.Token = token
if err := config.SaveFileConfig(&fc, configPath); err != nil {
fmt.Printf("Error writing config: %v\n", err)
os.Exit(1)
}
fmt.Printf("Config file created at %s\n", configPath)
}
func handleConfigPath() {
configPath := os.Getenv("PINCHTAB_CONFIG")
if configPath == "" {
configPath = config.DefaultConfigPath()
}
fmt.Println(configPath)
}
func handleConfigGet(path string) {
fc, _, err := config.LoadFileConfig()
if err != nil {
fmt.Printf("Error loading config: %v\n", err)
os.Exit(1)
}
value, err := config.GetConfigValue(fc, path)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
fmt.Println(value)
}
func handleConfigSet(path, value string) {
fc, configPath, err := config.LoadFileConfig()
if err != nil {
fmt.Printf("Error loading config: %v\n", err)
os.Exit(1)
}
if err := config.SetConfigValue(fc, path, value); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
fmt.Printf("Warning: new value causes validation error(s):\n")
for _, err := range errs {
fmt.Printf(" - %v\n", err)
}
fmt.Print("Save anyway? (y/N): ")
var response string
_, _ = fmt.Scanln(&response)
if response != "y" && response != "Y" {
return
}
}
if err := config.SaveFileConfig(fc, configPath); err != nil {
fmt.Printf("Error saving config: %v\n", err)
os.Exit(1)
}
fmt.Printf("Set %s = %s\n", path, value)
}
func handleConfigPatch(jsonPatch string) {
fc, configPath, err := config.LoadFileConfig()
if err != nil {
fmt.Printf("Error loading config: %v\n", err)
os.Exit(1)
}
if err := config.PatchConfigJSON(fc, jsonPatch); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
fmt.Printf("Warning: patch causes validation error(s):\n")
for _, err := range errs {
fmt.Printf(" - %v\n", err)
}
fmt.Print("Save anyway? (y/N): ")
var response string
_, _ = fmt.Scanln(&response)
if response != "y" && response != "Y" {
return
}
}
if err := config.SaveFileConfig(fc, configPath); err != nil {
fmt.Printf("Error saving config: %v\n", err)
os.Exit(1)
}
fmt.Println("Config patched successfully")
}
func handleConfigValidate() {
configPath := os.Getenv("PINCHTAB_CONFIG")
if configPath == "" {
configPath = config.DefaultConfigPath()
}
data, err := os.ReadFile(configPath)
if err != nil {
fmt.Printf("Error reading config file: %v\n", err)
os.Exit(1)
}
fc := &config.FileConfig{}
if err := json.Unmarshal(data, fc); err != nil {
fmt.Printf("Error parsing config: %v\n", err)
os.Exit(1)
}
if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
fmt.Printf("Config file has %d error(s):\n", len(errs))
for _, err := range errs {
fmt.Printf(" - %v\n", err)
}
os.Exit(1)
}
fmt.Printf("Config file is valid: %s\n", configPath)
}
|