Skip to content

Commit e2f9e6b

Browse files
authored
feat: confirm envd destroy when path and name are both empty (#1568)
* feat: fail `envd destroy` when path and name are both empty * fix: display user confirmation innstead of failing destroy * feat: additional comment for better clarity
1 parent ac0dd7e commit e2f9e6b

File tree

1 file changed

+40
-4
lines changed

1 file changed

+40
-4
lines changed

pkg/app/destroy.go

+40-4
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,13 @@
1515
package app
1616

1717
import (
18+
"bufio"
19+
"fmt"
20+
"os"
1821
"path/filepath"
1922

2023
"github.com/cockroachdb/errors"
24+
"github.com/mattn/go-isatty"
2125
"github.com/sirupsen/logrus"
2226
"github.com/urfave/cli/v2"
2327

@@ -51,19 +55,36 @@ var CommandDestroy = &cli.Command{
5155
Action: destroy,
5256
}
5357

58+
// Prompts the user to confirm an operation with [Y/n].
59+
// If the output is not tty, it will return false automatically.
60+
func confirm(prompt string) bool {
61+
isTerminal := isatty.IsTerminal(os.Stdout.Fd())
62+
if !isTerminal {
63+
return false
64+
}
65+
66+
reader := bufio.NewReader(os.Stdin)
67+
fmt.Printf("%s [Y/n] ", prompt)
68+
response, err := reader.ReadString('\n')
69+
if err != nil {
70+
return false
71+
}
72+
73+
response = response[:len(response)-1] // Remove newline character
74+
return response == "y" || response == "Y" || response == "yes" || response == "Yes"
75+
}
76+
5477
func destroy(clicontext *cli.Context) error {
5578
path := clicontext.Path("path")
5679
name := clicontext.String("name")
5780
if path != "" && name != "" {
5881
return errors.New("Cannot specify --path and --name at the same time.")
5982
}
60-
if path == "" && name == "" {
61-
path = "."
62-
}
83+
6384
var ctrName string
6485
if name != "" {
6586
ctrName = name
66-
} else {
87+
} else if path != "" {
6788
buildContext, err := filepath.Abs(path)
6889
if err != nil {
6990
return errors.Wrap(err, "failed to get absolute path of the build context")
@@ -72,7 +93,22 @@ func destroy(clicontext *cli.Context) error {
7293
if err != nil {
7394
return errors.Wrap(err, "failed to create an env name")
7495
}
96+
} else {
97+
// Both path and name are empty
98+
// Destroy the environment in the current directory only if user confirms
99+
buildContext, err := filepath.Abs(".")
100+
if err != nil {
101+
return errors.Wrap(err, "failed to get absolute path of the build context")
102+
}
103+
ctrName, err = buildutil.CreateEnvNameFromDir(buildContext)
104+
if err != nil {
105+
return errors.Wrap(err, "failed to create an env name")
106+
}
107+
if !confirm(fmt.Sprintf("Are you sure you want to destroy container %s in the current directory?", ctrName)) {
108+
return nil
109+
}
75110
}
111+
76112
context, err := home.GetManager().ContextGetCurrent()
77113
if err != nil {
78114
return errors.Wrap(err, "failed to get the current context")

0 commit comments

Comments
 (0)