AskForConfirmation asks the user for confirmation. A user must type in "yes" or "no" and then press enter. It has fuzzy matching, so "y", "Y", "yes", "YES", and "Yes" all count as confirmations. If the input is not recognized or interrupted, exit gracefully as "no".
(ctx context.Context, s string)
| 365 | // then press enter. It has fuzzy matching, so "y", "Y", "yes", "YES", and "Yes" all count as |
| 366 | // confirmations. If the input is not recognized or interrupted, exit gracefully as "no". |
| 367 | func AskForConfirmation(ctx context.Context, s string) (bool, error) { |
| 368 | reader := bufio.NewReader(os.Stdin) |
| 369 | |
| 370 | fmt.Printf("%s [y/n]: ", s) |
| 371 | |
| 372 | respCh := make(chan string, 1) |
| 373 | errCh := make(chan error, 1) |
| 374 | |
| 375 | go func() { |
| 376 | response, err := reader.ReadString('\n') |
| 377 | if err != nil { |
| 378 | errCh <- err |
| 379 | } else { |
| 380 | respCh <- response |
| 381 | } |
| 382 | }() |
| 383 | |
| 384 | select { |
| 385 | case <-ctx.Done(): |
| 386 | // Cobra caught SIGINT (Ctrl+C) and cancelled its root context |
| 387 | return false, nil |
| 388 | case err := <-errCh: |
| 389 | return false, err |
| 390 | case response := <-respCh: |
| 391 | response = strings.ToLower(strings.TrimSpace(response)) |
| 392 | if response == "y" || response == "yes" { |
| 393 | return true, nil |
| 394 | } |
| 395 | return false, nil |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | func CheckFileExists(path string) bool { |
| 400 | if _, err := os.Stat(path); os.IsNotExist(err) { |