fix(karmadactl): return error from DeleteConfirmation instead of calling os.Exit#7517
fix(karmadactl): return error from DeleteConfirmation instead of calling os.Exit#7517D3S-Gaurav wants to merge 1 commit into
Conversation
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request improves the robustness of the karmadactl utility by replacing abrupt process termination with proper error handling. By updating the DeleteConfirmation function to return errors instead of calling os.Exit, the application can now gracefully handle non-interactive environments like CI pipelines. Callers have been updated to propagate these errors, and new unit tests ensure the confirmation logic behaves correctly under various input conditions. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. Footnotes
|
|
Welcome @D3S-Gaurav! It looks like this is your first PR to karmada-io/karmada 🎉 |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
There was a problem hiding this comment.
Code Review
This pull request refactors the DeleteConfirmation utility to return an error instead of exiting the process and replaces its recursive logic with an iterative loop. Corresponding updates were made to the callers in the addons and deinit commands to handle the new signature, and unit tests were added. Feedback suggests using bufio.Scanner instead of fmt.Scanln to more robustly handle interactive user input, such as empty lines or multiple words.
| import ( | ||
| "fmt" | ||
| "os" | ||
| "strings" | ||
| ) | ||
|
|
||
| // DeleteConfirmation delete karmada resource confirmation | ||
| func DeleteConfirmation() bool { | ||
| fmt.Print("Please type (y)es or (n)o and then press enter:") | ||
| var response string | ||
| _, err := fmt.Scanln(&response) | ||
| if err != nil { | ||
| fmt.Println(err) | ||
| os.Exit(1) | ||
| } | ||
| // DeleteConfirmation prompts the user for a yes/no confirmation. | ||
| // It returns true if the user confirms with "y" or "yes", false on "n" or "no", | ||
| // and an error if stdin cannot be read (e.g. non-interactive environment). | ||
| func DeleteConfirmation() (bool, error) { | ||
| for { | ||
| fmt.Print("Please type (y)es or (n)o and then press enter:") | ||
| var response string | ||
| _, err := fmt.Scanln(&response) | ||
| if err != nil { | ||
| return false, fmt.Errorf("failed to read user confirmation: %w", err) | ||
| } | ||
|
|
||
| switch strings.ToLower(response) { | ||
| case "y", "yes": | ||
| return true | ||
| case "n", "no": | ||
| return false | ||
| default: | ||
| return DeleteConfirmation() | ||
| switch strings.ToLower(response) { | ||
| case "y", "yes": | ||
| return true, nil | ||
| case "n", "no": | ||
| return false, nil | ||
| default: | ||
| fmt.Println("invalid input, please type (y)es or (n)o") | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
The current implementation using fmt.Scanln is fragile for interactive CLI usage. It returns an error (such as "unexpected newline") if the user simply presses Enter, which causes the command to terminate immediately instead of re-prompting. It also fails if the user enters multiple words.
Using bufio.Scanner to read the entire line is more robust. It allows handling empty lines gracefully by continuing the loop and ensures that any extra input on the line is consumed.
import (
"bufio"
"fmt"
"os"
"strings"
)
// DeleteConfirmation prompts the user for a yes/no confirmation.
// It returns true if the user confirms with "y" or "yes", false on "n" or "no",
// and an error if stdin cannot be read (e.g. non-interactive environment).
func DeleteConfirmation() (bool, error) {
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Please type (y)es or (n)o and then press enter: ")
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return false, fmt.Errorf("failed to read user confirmation: %w", err)
}
return false, fmt.Errorf("failed to read user confirmation: unexpected EOF")
}
response := strings.TrimSpace(scanner.Text())
switch strings.ToLower(response) {
case "y", "yes":
return true, nil
case "n", "no":
return false, nil
case "":
continue
default:
fmt.Println("invalid input, please type (y)es or (n)o")
}
}
}There was a problem hiding this comment.
Pull request overview
This PR updates karmadactl’s delete confirmation helper to stop terminating the entire process on stdin read failures, and instead return an error so commands can surface a proper cobra error (improving CI/non-interactive behavior and testability).
Changes:
- Change
DeleteConfirmationsignature fromfunc() booltofunc() (bool, error)and replaceos.Exit(1)with an error return. - Replace recursive retry with an iterative
forloop and add an explicit invalid-input message. - Update
deinitandaddons disablecall sites to handle and propagate confirmation errors; add new table-driven tests.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| pkg/karmadactl/util/deleteconfirmation.go | Return (bool, error) instead of exiting; loop-based prompting with invalid-input feedback. |
| pkg/karmadactl/util/deleteconfirmation_test.go | New tests using os.Pipe() to simulate stdin and cover multiple input variants. |
| pkg/karmadactl/deinit/deinit.go | Update caller to handle (bool, error) and propagate errors. |
| pkg/karmadactl/addons/init/disable_option.go | Update caller to handle (bool, error) and propagate errors. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| fmt.Print("Please type (y)es or (n)o and then press enter:") | ||
| var response string | ||
| _, err := fmt.Scanln(&response) | ||
| if err != nil { | ||
| return false, fmt.Errorf("failed to read user confirmation: %w", err) | ||
| } |
| { | ||
| name: "DeleteConfirmation_WithEmptyInput_ReturnsError", | ||
| input: "", | ||
| wantOk: false, | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| // Exercises the retry loop: first input is unrecognized, | ||
| // second input is valid. Relies on the iterative for-loop | ||
| // rather than recursion. | ||
| name: "DeleteConfirmation_WithInvalidThenYes_ReturnsTrue", | ||
| input: "maybe\nyes\n", | ||
| wantOk: true, | ||
| wantErr: false, | ||
| }, |
| @@ -68,8 +68,14 @@ func (o *CommandAddonsDisableOption) Validate(args []string) error { | |||
| // Run start disable Karmada addons | |||
| func (o *CommandAddonsDisableOption) Run(args []string) error { | |||
| fmt.Printf("Disable Karmada addon %s\n", args) | |||
|
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #7517 +/- ##
==========================================
- Coverage 41.99% 41.99% -0.01%
==========================================
Files 879 879
Lines 54436 54444 +8
==========================================
+ Hits 22863 22865 +2
- Misses 29849 29851 +2
- Partials 1724 1728 +4
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
…ing os.Exit Signed-off-by: D3S-Gaurav <kumargauravrocco2724@gmail.com>
711293a to
0db0afb
Compare
|
Hi @chaosi-zju, |
What type of PR is this?
/kind bug
/kind cleanup
What this PR does / why we need it:
DeleteConfirmation()inpkg/karmadactl/util/deleteconfirmation.gocalledos.Exit(1)whenfmt.Scanlnfailed — in CI, piped stdin, or anynon-interactive environment. That's the wrong tool for a library function: callers
can't catch it, tests can't survive it, and the user gets no context about what
went wrong or which command triggered it.
Changes in this PR:
func DeleteConfirmation() booltofunc DeleteConfirmation() (bool, error)so callers can handle stdin failuresinstead of dying
os.Exit(1)is replaced withreturn false, fmt.Errorf("failed to read user confirmation: %w", err)default: return DeleteConfirmation()retry is replaced with aforloop; it also now prints"invalid input, please type (y)es or (n)o"sousers aren't left wondering why nothing happened
deinit/deinit.goandaddons/init/disable_option.go) areupdated to handle the
(bool, error)return and propagate failures throughcobra's
RunEdeleteconfirmation_test.gois new: 8 table-driven tests coveringy/n/yes/no,uppercase variants, empty stdin (the previously unkillable error path), and an
invalid-then-valid retry sequence
Which issue(s) this PR fixes:
Fixes #7516
Note for reviewer:
The stdin error path had no test coverage before this change because hitting it
called
os.Exit(1), which killed the test binary. The new tests useos.Pipe()to swap out stdin — no subprocess, no PTY needed.
A follow-up worth considering (out of scope here): inject
io.Readerandio.WriterintoDeleteConfirmation()to remove the dependency onos.Stdinand
os.Stdoutentirely.Does this PR introduce a user-facing change?: