15
15
package app
16
16
17
17
import (
18
+ "bufio"
19
+ "fmt"
20
+ "os"
18
21
"path/filepath"
19
22
20
23
"github.com/cockroachdb/errors"
24
+ "github.com/mattn/go-isatty"
21
25
"github.com/sirupsen/logrus"
22
26
"github.com/urfave/cli/v2"
23
27
@@ -51,19 +55,36 @@ var CommandDestroy = &cli.Command{
51
55
Action : destroy ,
52
56
}
53
57
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
+
54
77
func destroy (clicontext * cli.Context ) error {
55
78
path := clicontext .Path ("path" )
56
79
name := clicontext .String ("name" )
57
80
if path != "" && name != "" {
58
81
return errors .New ("Cannot specify --path and --name at the same time." )
59
82
}
60
- if path == "" && name == "" {
61
- path = "."
62
- }
83
+
63
84
var ctrName string
64
85
if name != "" {
65
86
ctrName = name
66
- } else {
87
+ } else if path != "" {
67
88
buildContext , err := filepath .Abs (path )
68
89
if err != nil {
69
90
return errors .Wrap (err , "failed to get absolute path of the build context" )
@@ -72,7 +93,22 @@ func destroy(clicontext *cli.Context) error {
72
93
if err != nil {
73
94
return errors .Wrap (err , "failed to create an env name" )
74
95
}
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
+ }
75
110
}
111
+
76
112
context , err := home .GetManager ().ContextGetCurrent ()
77
113
if err != nil {
78
114
return errors .Wrap (err , "failed to get the current context" )
0 commit comments