package main import ( "bufio" "fmt" "os" "strings" ) // handleBatch executes commands from a file func (c *KVSClient) handleBatch(args []string, executor func(string) bool) { if len(args) < 1 { fmt.Println(red("Usage: batch [--continue-on-error]")) fmt.Println(" source [--continue-on-error]") return } filename := args[0] file, err := os.Open(filename) if err != nil { fmt.Println(red("Error opening file:"), err) return } defer file.Close() scanner := bufio.NewScanner(file) lineNum := 0 successCount := 0 errorCount := 0 skippedCount := 0 for scanner.Scan() { lineNum++ line := strings.TrimSpace(scanner.Text()) // Skip empty lines and comments if line == "" || strings.HasPrefix(line, "#") { skippedCount++ continue } // Execute the command fmt.Printf(cyan("[%d]")+" %s\n", lineNum, line) // Block exit/quit commands in batch mode parts := parseCommand(line) if len(parts) > 0 && (parts[0] == "exit" || parts[0] == "quit") { fmt.Println(yellow("Note: exit/quit ignored in batch mode")) skippedCount++ continue } // Execute command executor(line) successCount++ } if err := scanner.Err(); err != nil { fmt.Println(red("Error reading file:"), err) return } // Print summary fmt.Println() fmt.Println(cyan("Batch execution complete:")) fmt.Printf(" Total lines: %d\n", lineNum) fmt.Printf(" Executed: %s\n", green(fmt.Sprintf("%d", successCount))) fmt.Printf(" Skipped: %d (empty/comments)\n", skippedCount) if errorCount > 0 { fmt.Printf(" Errors: %s\n", red(fmt.Sprintf("%d", errorCount))) } }