-
Notifications
You must be signed in to change notification settings - Fork 152
/
survey.go
95 lines (81 loc) · 2.47 KB
/
survey.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package survey
import (
"fmt"
"path/filepath"
"github.com/AlecAivazis/survey/v2"
petname "github.com/dustinkirkland/golang-petname"
"github.com/spf13/afero"
"github.com/raystack/optimus/internal/utils"
)
const (
answerYes = "Yes"
answerNo = "No"
)
// AskWorkingDirectory asks and returns the directory where the new spec folder should be created
func AskWorkingDirectory(specFS afero.Fs, rootDirPath string) (string, error) {
directories, err := afero.ReadDir(specFS, rootDirPath)
if err != nil {
return "", err
}
if len(directories) == 0 {
return rootDirPath, nil
}
currentFolder := ". (current directory)"
subDirectories := []string{currentFolder}
for _, dir := range directories {
if !dir.IsDir() {
continue
}
dirItems, err := afero.ReadDir(specFS, filepath.Join(rootDirPath, dir.Name()))
if err != nil {
return "", err
}
var alreadyOccupied bool
for _, dirItem := range dirItems {
specFileNames := []string{"resource.yaml", "job.yaml"}
if utils.ContainsString(specFileNames, dirItem.Name()) {
alreadyOccupied = true
break
}
}
if alreadyOccupied {
continue
}
subDirectories = append(subDirectories, dir.Name())
}
messageStr := "Select directory to save specification?"
if rootDirPath != "" {
messageStr = fmt.Sprintf("%s [%s]", messageStr, rootDirPath)
}
var selectedDir string
if err := survey.AskOne(&survey.Select{
Message: messageStr,
Default: currentFolder,
Help: "Optimus helps organize specifications in sub-directories.\nPlease select where you want this new specification to be stored",
Options: subDirectories,
}, &selectedDir); err != nil {
return "", err
}
if selectedDir != currentFolder {
return AskWorkingDirectory(specFS, filepath.Join(rootDirPath, selectedDir))
}
return rootDirPath, nil
}
// AskDirectoryName asks and returns the directory name of the new spec folder
func AskDirectoryName(root string) (string, error) {
standardizedRoot := root
if standardizedRoot == "" {
standardizedRoot = "."
}
numberOfWordsToGenerate := 2
sampleDirectoryName := petname.Generate(numberOfWordsToGenerate, "_")
var selectedDir string
if err := survey.AskOne(&survey.Input{
Message: fmt.Sprintf("Provide new directory name to create for this spec? [%s]", standardizedRoot),
Default: sampleDirectoryName,
Help: fmt.Sprintf("A new directory will be created under [%s]", filepath.Join(root, sampleDirectoryName)),
}, &selectedDir); err != nil {
return "", err
}
return selectedDir, nil
}